Axios OPTIONS instead of POST Request. Express Rest API (CORS)

前提是你 提交于 2019-12-12 12:50:26

问题


Im trying to use Axios (and VueJs) to make a Cross Origin POST Request to my Rest Api (running on localhost). Instead of doing a POST request, it actually does a OPTIONS request to my Rest Api. This circumvents a middleware function that checks for a token and return 403.

This is the login 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? 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)

CORS Middleware:

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();
    }
});

来源:https://stackoverflow.com/questions/47762097/axios-options-instead-of-post-request-express-rest-api-cors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!