CORS政策:对预检请求的响应未通过访问控制检查 [英] CORS policy: Response to preflight request doesn't pass access control check

查看:235
本文介绍了CORS政策:对预检请求的响应未通过访问控制检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试通过浏览器对我的API做一个简单的post方法,但失败了.当我对邮递员做同样的事情时,POST方法就没问题了.它返回一个json字符串并返回2个cookie.

I am currently trying to do a simple post method to my API through the browser and it fails. When I do the same on postman, the POST method goes without problem. It returns a json string and returns 2 cookies.

我试图像在SO上那样在中间件中设置标头:

I have tried to set the headers in the middleware like I found on SO:

router.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    console.log('Something is happening.');
    next(); // make sure we go to the next routes and don't stop here
});

不幸的是,这不能解决问题,因此我进行了更多研究,发现了一个有关Cors的NPM软件包:

Unfortunately this did not solve the issue, so I went out for more research and found a NPM package about Cors: https://www.npmjs.com/package/cors

所以我仔细阅读了安装指南并将其添加到我的解决方案中:

so I went through the installation guide and added it to my solution:

....
var cors = require('cors');
....
app.use(cors());
app.options('*', cors())
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

也没有运气.

我几乎没有主意,也不知道这里可能是什么问题.

I am pretty much out of ideas, and have no clue what could be the issue here.

这是客户端:

login() {
      if(this.input.username != '' && this.input.password != '') {
          //We should execute our Axios here. 

          axios.post('http://localhost:8080/api/user/login',{
            username:this.input.username,
            password:this.input.password   
          })
            .then(function (response) {
                // handle success
                console.log(JSON.stringify(response.data));
                console.log(response.status);
                console.log(response.headers);
                //Router.push('Dashboard')
            })
            .catch(function (error) {
                // handle error
                console.log(JSON.stringify(error.data));
                console.log(error.status);
                console.log(error.headers);
            })
            .then(function () {
                // always executed
            });
      } else {
          console.log('A username and password must be present')
      }
}

但这对我来说似乎还可以.

but that seems to be OK to me.

Post方法本身:

router.route('/user/login/')
    .post(function(req, res) {
        var user = new User();      // create a new instance of the user model
        user.username = req.body.username;  // set the users name (comes from the request)
        user.password = req.body.password;
        User.findOne({ username: user.username}, function(err, dbuser) {
            if (err)
                res.send(err);
                console.log('Error');

            bcrypt.compare(user.password, dbuser.password, function(err, compareResult) {
                console.log('Match!')
                // create a token
                var token = jwt.sign({ username: user.username }, secret, {
                    expiresIn: 86400 // expires in 24 hours
                });
                res.cookie("test", user.username);
                res.status(200).send({ auth: true, token: token });
                console.log(token);
            });
        });
});

推荐答案

使用cors模块时,这些设置是我用来允许所有与cors相关的设置

When using the cors module here are the settings I use to allow everything cors related

const corsOptions = {
  origin: true,
  methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
  credentials: true,
  preflightContinue: true,
  maxAge: 600,
};
app.options('*', cors(corsOptions));
app.use(cors(corsOptions));

这篇关于CORS政策:对预检请求的响应未通过访问控制检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆