jQuery.ajax发送OPTIONS和POST,如何处理Express.js(Node.js) [英] jQuery.ajax sending both OPTIONS and POST, how to handle with Express.js (Node.js)
问题描述
每当我的应用程序向服务器发送ajax请求时:
Whenever my application sends an ajax request to the server:
$.ajax({
url: config.api.url + '/1/register',
type: 'POST',
contentType: 'application/json',
data: /* some JSON data here */,
/* Success and error functions here*/
});
它发送以下两个请求:
Request URL:https://api.example.com/1/register
Request Method:OPTIONS
Status Code:404 Not Found
随着适当的 POST
与所有的数据。因为我处理这样的路由:
Followed by the appropriate POST
with all of the data. Since I handle the routes as such:
expressApp.post('/1/register', UserController.register);
而且没有一个 .options
这条路线总是以 404
结束。几乎所有的方法都是一样的。 这个问题谈谈一下在接受的两个答案中,但我不太确定该怎么做。
And do not have a .options
for this route, it always ends up in 404
. It's the same for nearly all methods. This question talks a little bit about it in the two answers below the accepted one, but I'm not quite sure what to make of it.
我该如何处理?我应该添加 .options
route,如果是这样做,应该怎么办?
How can I handle this? Should I be adding .options
route and if so what should it do?
推荐答案
我今天才处理这件事。以下是解决问题的要点。
I actually dealt with this just today. Here's the gist which solved my problem.
Node.js跨原始POST。您应该首先响应OPTIONS请求。
Node.js cross-origin POST. You should response for OPTIONS request first. Something like this.
if (req.method === 'OPTIONS') {
console.log('!OPTIONS');
var headers = {};
// IE8 does not allow domains to be specified, just the *
// headers["Access-Control-Allow-Origin"] = req.headers.origin;
headers["Access-Control-Allow-Origin"] = "*";
headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
headers["Access-Control-Allow-Credentials"] = false;
headers["Access-Control-Max-Age"] = '86400'; // 24 hours
headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";
res.writeHead(200, headers);
res.end();
} else {
//...other requests
}
< hr>
将此放在您遇到此问题的请求的任何地方。我将它设置为一个 checkIfOption
函数变量,并调用它:
Put this in anywhere that you have a request with this problem. I set it to a checkIfOption
function variable and call it like so:
app.all('/', function(req, res, next) {
checkIfOption(req, res, next);
});
代替 // ...其他请求
我调用 next();
这对我来说很好。
这篇关于jQuery.ajax发送OPTIONS和POST,如何处理Express.js(Node.js)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!