CORS - Angular 和 Express 的 http OPTIONS 错误

CORS - http OPTIONS error with Angular and Express

我正在尝试从 Angularjs 客户端为我的 API 创建一个 POST,我在服务器上有这个配置,它是另一个域中的 运行 :

app.use(function(req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, OPTIONS, DETELE');
  res.setHeader('Access-Control-Allow-Headers', '*');
  next();
});

发送到服务器的headers是:

OPTIONS /api/authenticate HTTP/1.1
Host: xxxx.herokuapp.com
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://127.0.0.1:5757
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36
Access-Control-Request-Headers: accept, content-type
Accept: */*
Referer: http://127.0.0.1:5757/login
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en,es;q=0.8,gl;q=0.6,pt;q=0.4

响应headers是:

HTTP/1.1 403 Forbidden
Server: Cowboy
Connection: keep-alive
X-Powered-By: Express
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS, DETELE
Access-Control-Allow-Headers: X-Requested-With,content-type,Authorization
Content-Type: application/json; charset=utf-8
Content-Length: 47
Etag: W/"2f-5f255986"
Date: Sun, 20 Sep 2015 19:26:56 GMT
Via: 1.1 vegur

我在 Chrome 控制台中得到的是:

angular.js:9814 OPTIONS http://xxxxx.herokuapp.com/api/authenticate 
XMLHttpRequest cannot load http://xxxx.herokuapp.com/api/authenticate. Response for preflight has invalid HTTP status code 403

事实上大多数浏览器出于安全原则不允许客户端js代码从同一主机请求资源。

但是,当资源所有者通过添加跨源资源共享 headers 作为响应来告诉客户端浏览器他的共享资源时,这是允许的。

不要猜测 headers 使用 cors 包 - 它会为你完成所有肮脏的工作。

npm install cors --save

然后:

var express = require('express')
  , cors = require('cors')
  , app = express();

app.use(cors());

就这些了:)

其他文档在这里:https://www.npmjs.com/package/cors

我明白了,这个话题有点老了,但我发现你的 ACCESS-CONTROL-ALLOW-METHODS 有一点错别字。

只是想与其他在复制和粘贴时遇到类似问题的用户分享:

Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS, DETELE

DELETE 中有错别字。