【问题标题】:CORS policy: Response to preflight request doesn't pass access control checkCORS 策略:对预检请求的响应未通过访问控制检查
【发布时间】:2018-12-02 05:54:38
【问题描述】:

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

我尝试在中间件中设置标头,就像我在 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 包:https://www.npmjs.com/package/cors

所以我浏览了安装指南并将其添加到我的解决方案中:

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

同样,没有运气。

我几乎没有想法,不知道这里可能是什么问题。

这里是客户端:

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')
      }
}

但这对我来说似乎没问题。

发布方法本身:

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

【问题讨论】:

    标签: javascript express vue.js


    【解决方案1】:

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

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

    【讨论】:

    • 为什么需要将方法设置为默认值?
    猜你喜欢
    • 2021-05-05
    • 2020-09-30
    • 2019-10-22
    • 2019-04-17
    • 2019-09-09
    • 2019-01-04
    • 1970-01-01
    • 2020-01-23
    相关资源
    最近更新 更多