简体   繁体   中英

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

Axios will sometimes send an OPTIONS request as part of a cors preflight if it doesn't know the Content-Type of a request.

You can get explicitly specify the Content-Type when you build the request, and then it should send your POST request as expected.

Instead of axios.post(url, params) , try:

axios.post(url, params, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM