简体   繁体   English

Angular 2 CORS 问题

[英]Angular 2 CORS issues

I have the following Angular 2 http request;我有以下 Angular 2 http 请求;

 const endpoint = '<auth_url>'; const body = { prompt: 'consent', grant_type: 'authorization_code', redirect_uri: '<redirect_url>', code: '<authorization_code>' }; const headers = new Headers(); headers.append('Authorization', 'Basic <auth>'); headers.append('Content-Type', 'application/x-www-form-urlencoded') const options = new RequestOptions({ headers }); this.http.post(endpoint, body, { headers: headers }) .map(res => res.json()) .subscribe( data => console.log(JSON.stringify(data)), error => console.error(JSON.stringify(error)), () => console.log('Request complete') );

This is connecting to a node-oidc-provider which has been attached to an ExpressJS instance, the issue I am having is with CORS as the request ends up as OPTIONS on the server because of preflight.这是连接到已附加到 ExpressJS 实例的node-oidc-provider ,我遇到的问题是 CORS,因为由于预检,请求最终作为服务器上的 OPTIONS。 This shouldn't be the case as I have specified the Content-Type header as seen above.这不应该是这种情况,因为我已经指定了上面看到的Content-Type标头。 Annoyingly I am trying to figure out whether this is an issue with the server or my Angular2 code?烦人的是,我想弄清楚这是服务器的问题还是我的 Angular2 代码的问题?

Would I need to explicitly enable CORS on an ExpressJS application and if not, why would setting the correct header on the POST have no effect?我是否需要在 ExpressJS 应用程序上显式启用 CORS,如果没有,为什么在 POST 上设置正确的标头无效?

Yes, you need to enable CORS on the server side.是的,您需要在服务器端启用 CORS。 That is if you have control on the server.也就是说,如果您可以控制服务器。 Here are the Headers that should be returned from the server to enable CORS以下是应从服务器返回以启用 CORS 的标头

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,POST,PUT,DELETE
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept

You can share some details about your server like if you want to add these headers from the code or in the WebServer itself.您可以共享有关您的服务器的一些详细信息,例如您是否想从代码或 WebServer 本身添加这些标头。

Regarding the question about the reason why setting the headers in the POST request has no effect.关于为什么在POST请求中设置headers没有效果的问题。 The browser issues an OPTION request before your XHTTP request to ask the permission from the server about accepting CORS.浏览器在您的 XHTTP 请求之前发出一个 OPTION 请求,以询问服务器关于接受 CORS 的许可。

So, if you have control on the server, then you can add the headers I mentioned before.因此,如果您可以控制服务器,那么您可以添加我之前提到的标头。 If not, then you can use some browser plugins to overcome this check.如果没有,那么您可以使用一些浏览器插件来克服此检查。

Here is how the network tab in the developer tools should look like这是开发人员工具中的网络选项卡的外观

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM