【问题标题】:Setting HTTP Headers in Angular 13 does not seem to work right在 Angular 13 中设置 HTTP 标头似乎无法正常工作
【发布时间】:2021-12-29 04:30:41
【问题描述】:

如果我这样设置标头,那么我的 API 会返回 415,因为 HTTP 请求是使用 text/plain 的内容类型发送的

let headers: HttpHeaders = new HttpHeaders();

如果我将代码放在下面,那么它会以某种方式弄乱 Origin 标头,因为在解决此问题之前我已经解决了 CORS 违规问题。

if (!headers.has('content-type')) {
    headers = headers.append('content-type', 'application/json')
}
else{
    headers = headers.set('content-type', 'application/json')
}

我发现的所有内容都表明我正确设置了标题,但我无法解释为什么会遇到这些问题。

有什么想法吗?

Package.json 依赖项:

    "@angular/animations": "~13.0.0",
    "@angular/common": "~13.0.0",
    "@angular/compiler": "~13.0.0",
    "@angular/core": "~13.0.0",
    "@angular/forms": "~13.0.0",
    "@angular/platform-browser": "~13.0.0",
    "@angular/platform-browser-dynamic": "~13.0.0",
    "@angular/router": "~13.0.0",
    "bootstrap": "^5.1.3",
    "jquery": "^3.6.0",
    "popper": "^1.0.1",
    "rxjs": "~7.4.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },

【问题讨论】:

  • 您是否为此使用了拦截器?如果不是,请尝试添加标题作为一种良好做法的正确位置。其次,当您在标题中添加来源时,请显示更多代码,以便我可以看到可能出现的问题

标签: angular angular-httpclient angular-http


【解决方案1】:

我最终需要调整我的 API 以允许在飞行前调用中使用 Content-Type 标头。

            services.AddCors(options =>
            {
            options.AddPolicy(name: MyAllowSpecificOrigins,
                builder =>
                {
                    builder.WithOrigins(Configuration.GetValue<string>("smWebUrl"));
                    builder.WithHeaders("Content-Type");
                });
            });

【讨论】:

    猜你喜欢
    • 2018-08-26
    • 1970-01-01
    • 2017-09-04
    • 2012-05-06
    • 2013-02-17
    • 2017-10-09
    • 2017-08-03
    • 2014-05-02
    • 2011-09-11
    相关资源
    最近更新 更多