javascript - Angular 7 HttpHeaders CORS 问题

标签 javascript angular cors angular7

我正在尝试使用 UPS 的包裹评级 API,我可以在 Postman 中使用它,但不能在网络浏览器上使用。我知道 postman 不担心 CORS。

我有这个帖子请求:

getRate() {
    return this.http.post(this.upsUrlTest, this.upsConfig, this.postOptions);
}

我的 3 个变量是:

upsUrlTest = 'https://wwwcie.ups.com/ship/1801/rating/Rate';
upsConfig = {...This is filled out and working in postman...}
postOptions = {
  headers: new HttpHeaders({
    transId: '0001',
    transactionSrc: '##########',  //Actual information is correct
    AccessLicenseNumber: '########',
    username: '#########',
    password: '#########',
    // These last two are where I believe the problem is
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': 'x-requested-with, x-requested-by',
  })
};

我收到这样的回复: enter image description here

奇怪的是,在出现 CORS 问题之前我就收到了 404。我不确定我的格式是否错误,或者这里是否还有其他问题。

另一个注意事项:我正在本地主机上运行这个 Angular 项目,但是当我将其放在我的服务器上时,我遇到了同样的问题。

编辑:仅仅因为这与 CORS 有关,并不意味着它与我的情况重复。在这种情况下,指向提议的原件的链接就足够了。

最佳答案

使用 Angular,您需要在后端/目标 URL 中启用 CORS 策略。

默认情况下,在我的 PHP 项目中,我使用以下 header :

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, PUT, DELETE, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding, Authorization, X-Requested-With");

关于 Angular 的另一个有趣的事情是,在执行 Http 请求之前,它会执行一个名为“预检”的功能,该功能无非是检查目的地是否可以接收请求。

(抱歉我的英语不好,我是巴西人,我正在花时间练习我的语言)

关于javascript - Angular 7 HttpHeaders CORS 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55872746/

相关文章:

javascript - 移动Webkit和Hammer JS上的多个元素响应触摸事件

javascript - 如何使用 Angular 2发出链接请求(不同数量)

heroku - Angular 2 : X-XSRF-TOKEN is not allowed by Access-Control-Allow-Headers

具有 Windows 身份验证预检问题的 Angular 4 HTTP POST

firefox - 在不安装插件的情况下禁用 Firefox 同源策略

javascript - XMLHttpRequest 在 $.ajax 工作的地方给出 CORS 错误

javascript - 不区分大小写的 javascript 替换考虑单词边界的正则表达式

javascript - 如何将对象文字作为键值对推送到数组?

angular - 无法绑定(bind)到 'ngValue',因为它不是已知的 native 属性”

angular - TS2345 : Argument of type 'string' is not assignable to parameter of type 'never'