Jan*_*utz 5 rest express vue.js axios
我尝试使用 Axios (和 VueJs)向我的 Rest Api (在本地主机上运行)发出跨源 POST 请求。它实际上没有执行 POST 请求,而是向我的 Rest Api 执行 OPTIONS 请求。这绕过了检查令牌并返回 403 的中间件函数。
这是登录功能
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});
}
}
})
});
Run Code Online (Sandbox Code Playgroud)
如何让 Axios 发出正确的 POST 请求?我尝试了这个 hack,因为我首先认为 OPTIONS 请求只是一个预检,但是在我返回 200(或 204)后就没有请求了
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();
}
});
Run Code Online (Sandbox Code Playgroud)
如果 Axios 不知道请求的 Content-Type,它有时会在 cors 预检过程中发送 OPTIONS 请求。
您可以在构建请求时显式指定 Content-Type,然后它应该按预期发送您的 POST 请求。
而不是
axios.post(url, params),请尝试:
axios.post(url, params, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2368 次 |
| 最近记录: |