我已经在用于node.js的快速框架上编写了REST API,该API可以处理来自Chrome中的js控制台的请求以及URL栏等。域(CORS)。
由javascript前端自动发出的第一个请求是对/ api / search?uri =的,并且似乎对“预检” OPTIONS请求失败。
在我的express应用中,我使用以下方法添加了CORS标头:
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
};
和:
app.configure(function () {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(allowCrossDomain);
app.use(express.static(path.join(application_root, "public")));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
从Chrome控制台中,我得到以下标题:
请求网址:http://furious-night-5419.herokuapp.com/api/search?uri = http%3A%2F%2Flocalhost%3A5000%2Fcollections%2F1%2Fdocuments%2F1
请求方法:OPTIONS
状态码:200 OK
请求标题
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:origin, x-annotator-auth-token, accept
Access-Control-Request-Method:GET
Connection:keep-alive
Host:furious-night-5419.herokuapp.com
Origin:http://localhost:5000
Referer:http://localhost:5000/collections/1/documents/1
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5
查询字符串参数
uri:http://localhost:5000/collections/1/documents/1
响应标题
Allow:GET
Connection:keep-alive
Content-Length:3
Content-Type:text/html; charset=utf-8
X-Powered-By:Express
这看起来像API应用程序发送的标题不足吗?
谢谢。
OPTIONS
。有人可以帮我理解为什么不只处理POST
方法而不是同时处理POST
和OPTIONS
方法吗?