发送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();
这对我很有用。
- 使用jQuery / JS检查图像HTTP状态代码?
- 在jQuery中使用X-HTTP-Method-Override?
- contentType:’application / json’和POST方法(JavaScript)
- CORS预检请求返回“403 Forbidden”; 后续请求然后仅在Chrome中发送
- 如何使用ExpressJS确定正确的Accept Content-Type
- 更改Ajax POST的引用者
- 删除jQuery.ajaxSetup中设置的特定请求标头
- 在Javascript运行PHP之后获取URL的内容(文本)
- 是否可以从JavaScript中的HTTP响应头获取Set-Cookie值?