发送OPTIONS和POST的jQuery.ajax,如何处理Express.js(Node.js)

每当我的应用程序向服务器发送ajax请求时:

$.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与所有数据。 因为我这样处理路线:

 expressApp.post('/1/register', UserController.register); 

并且没有针对此路线的.options ,它总是在404结束。 几乎所有方法都是一样的。 这个问题在接受的答案之下的两个答案中谈了一点,但我不太清楚该怎么做。

我怎么处理这个? 我应该添加.options路由,如果是的话应该怎么办?

我实际上是在今天处理这个问题。 这是解决我的问题的要点 。


Node.js跨源POST。 您应首先响应OPTIONS请求。 像这样的东西。

 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 } 

把它放在有这个问题请求的任何地方。 我将它设置为checkIfOption函数变量并像这样调用它:

 app.all('/', function(req, res, next) { checkIfOption(req, res, next); }); 

并且在//...other requests的位置我调用next();

这对我很有用。