首页 > 解决方案 > 将 Curl 请求转换为 Angular 请求

问题描述

我对这个 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 });

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

标签: angularangular-httpclient

解决方案


试试这个代码:

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
    },

推荐阅读