【问题标题】:Convert Curl request to Angular request将 Curl 请求转换为 Angular 请求
【发布时间】:2021-02-06 11:05:48
【问题描述】:

我对这个 CURL 请求有疑问。如果我通过终端发送它可以正常工作,但是当我将其转换为 Angular HTTP 客户端调用时它不起作用。

卷曲:

curl --location --request PUT '<some_url>' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--data-raw '{
    "status": "CONFIRMED"
}'

角度:

const headers = new HttpHeaders()
  .set('Content-Type', 'application/json')
  .set('Accept', 'application/json; charset=UTF-8');

const b = {
  status: 'CONFIRMED'
};

return this.http.put(some_url, b, { headers });

错误: CORS 策略已阻止从源“http://localhost:4200”访问 :预检响应中的 Access-Control-Allow-Methods 不允许方法 PUT。

【问题讨论】:

    标签: angular angular-httpclient


    【解决方案1】:

    试试这个代码:

    const httpOptions = {
          headers: new HttpHeaders({
            'Content-Type': 'application/json',
            'Accept', 'application/json; charset=UTF-8'
          }),
        };
    const b = {
      status: 'CONFIRMED'
    };
    return this.http<any>(some_url, b,httpOptions)
          .pipe(catchError(this.errorHandler));
    

    使用 proxy.config.json 文件

     {
          "/api/*": {
            "target": "http://backendurl",
            "secure": false,
            "changeOrigin": true
          }
        }
    

    在serve->options下添加代理配置angular.json:

      "serve": {
        "builder": "@angular-devkit/build-angular:dev-server",
        "options": {
          "browserTarget": "your-application-name:build",
          "proxyConfig": "src/proxy.conf.json" // add this ligne
        },
    

    【讨论】:

    • ` const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Accept', 'application/json; charset=UTF-8' }), } ; ` 没有必要,除此之外,一切都会正常工作,但是。
    【解决方案2】:
    return this.http.put(some_url, body);
    

    应该可以。

    【讨论】:

    【解决方案3】:

    一定要在put()之后调用subscribe(),否则请求根本不会被执行。

    【讨论】:

    • 我正在这样做
    • 那你应该详细说明“不起作用”这个词。
    猜你喜欢
    • 1970-01-01
    • 2018-04-16
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-17
    • 2015-08-10
    • 2023-04-02
    相关资源
    最近更新 更多