我有以下 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')
);
这是连接到已附加到 ExpressJS 实例的 node-oidc-provider
,我遇到的问题是 CORS,因为由于预检,请求最终在服务器上作为选项。情况不应该是这样,因为我已经指定了 Content-Type
header ,如上所示。令人烦恼的是,我试图弄清楚这是否是服务器或我的 Angular2 代码的问题?
我是否需要在 ExpressJS 应用程序上显式启用 CORS?如果不需要,为什么在 POST 上设置正确的 header 没有效果?
最佳答案
是的,您需要在服务器端启用 CORS。也就是说,如果您可以控制服务器。 以下是启用 CORS 时应从服务器返回的 header
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,POST,PUT,DELETE
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
您可以共享有关服务器的一些详细信息,例如您是否想从代码或 Web 服务器本身添加这些 header 。
关于为什么在POST请求中设置header没有效果的问题。浏览器在您的 XHTTP 请求之前发出 OPTION 请求,以请求服务器允许接受 CORS。
因此,如果您可以控制服务器,那么您可以添加我之前提到的 header 。如果没有,那么您可以使用一些浏览器插件来克服此检查。
开发者工具中的网络选项卡应如下所示
关于node.js - Angular 2 CORS 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42022266/