[英]Axios OPTIONS instead of POST Request. Express Rest API (CORS)
Im trying to use Axios (and VueJs) to make a Cross Origin POST Request to my Rest Api (running on localhost).我试图使用 Axios(和 VueJs)向我的 Rest Api(在本地主机上运行)发出跨域 POST 请求。 Instead of doing a POST request, it actually does a OPTIONS request to my Rest Api.
它实际上不是执行 POST 请求,而是对我的 Rest Api 执行 OPTIONS 请求。 This circumvents a middleware function that checks for a token and return 403.
这绕过了检查令牌并返回 403 的中间件 function。
This is the login function这是登录 function
router.post('/login', (req, res) => {
User.authUser(req.body, (err, user) => {
var passwordIsValid = bcrypt.compareSync(req.body.password, user.password);
if (err) throw err;
if (!user) {
res.json({ success: false, message: 'User nicht gefunden' });
} else if (user) {
if (!passwordIsValid) {
res.json({ success: false, message: 'Falsches Passwort' });
} else {
const payload = {
admin: user.admin
};
var token = jwt.sign(payload, config.secret, {
expiresIn: 86400
});
res.json({success: true, message: 'Token!', token: token});
}
}
})
});
How can I get Axios to make a proper POST request?如何让 Axios 发出正确的 POST 请求? I tried this hack, because I first thought the OPTIONS Request was just a preflight, but there is no request after I return 200 (or 204)
我尝试了这个 hack,因为我首先认为 OPTIONS 请求只是一个预检,但是在我返回 200(或 204)之后没有请求
CORS Middleware: CORS 中间件:
app.use(function(req, res, next) { //set Response Headers
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
if ('OPTIONS' == req.method) {
res.send(204);
}
else {
next();
}
});
Axios will sometimes send an OPTIONS request as part of a cors preflight if it doesn't know the Content-Type of a request.如果 Axios 不知道请求的 Content-Type,它有时会发送一个 OPTIONS 请求作为 cors 预检的一部分。
You can get explicitly specify the Content-Type when you build the request, and then it should send your POST request as expected.您可以在构建请求时明确指定 Content-Type,然后它应该按预期发送您的 POST 请求。
Instead of axios.post(url, params)
, try:而不是
axios.post(url, params)
,尝试:
axios.post(url, params, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.