Mat*_*att 0 jquery post http-headers node.js express
每当我的应用程序向服务器发送ajax请求时:
$.ajax({
url: config.api.url + '/1/register',
type: 'POST',
contentType: 'application/json',
data: /* some JSON data here */,
/* Success and error functions here*/
});
Run Code Online (Sandbox Code Playgroud)
它发送以下两个请求:
Request URL:https://api.example.com/1/register
Request Method:OPTIONS
Status Code:404 Not Found
Run Code Online (Sandbox Code Playgroud)
其次是适当POST
的所有数据.因为我这样处理路线:
expressApp.post('/1/register', UserController.register);
Run Code Online (Sandbox Code Playgroud)
并没有.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
}
Run Code Online (Sandbox Code Playgroud)
把它放在有这个问题请求的任何地方.我将它设置为一个checkIfOption
函数变量,并调用它:
app.all('/', function(req, res, next) {
checkIfOption(req, res, next);
});
Run Code Online (Sandbox Code Playgroud)
而在//...other requests
我打电话的地方next();
这对我很有用.
归档时间: |
|
查看次数: |
3111 次 |
最近记录: |