Angular 2 CORS问题

时间:2017-02-03 10:38:30

标签: node.js http angular post cors

我有以下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,因为预检将请求最终作为服务器上的OPTIONS。这不应该是这种情况,因为我已经指定了Content-Type标题,如上所示。令人讨厌的是我想弄清楚这是服务器还是我的Angular2代码的问题?

我是否需要在ExpressJS应用程序上显式启用CORS,如果没有,为什么在POST上设置正确的标头没有效果?

1 个答案:

答案 0 :(得分:2)

是的,您需要在服务器端启用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

您可以分享有关服务器的一些详细信息,例如,如果要从代码或WebServer本身添加这些标头。

关于在POST请求中设置标头的原因无效的问题。浏览器在XHTTP请求之前发出OPTION请求,要求服务器提供有关接受CORS的权限。

因此,如果您对服务器有控制权,那么您可以添加我之前提到的标题。如果没有,那么您可以使用一些浏览器插件来克服此检查。

以下是开发人员工具中的网络选项卡应如何显示

enter image description here