CORS 与 Angular 和 Express - 在 Postman 中工作但不在浏览器中工作

Ras*_*uls 5 node.js cors express angular

我有一个与 CORS 相关的问题(我认为),当我从邮递员发送登录帖子请求时,它成功了。当我尝试使用我的 angular 2 前端应用程序登录时,请求状态似乎是 200,但没有任何反应,并且在控制台中我收到一条奇怪的消息,我的 localhost:4200 不被允许,我该如何解决这个问题?

角度http方法

 authenticateUser(user){
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post('http://localhost:3000/api/authenticate', user, {headers: headers})
    .map(res => res.json());
  }
Run Code Online (Sandbox Code Playgroud)

来自控制台的错误消息。 在此处输入图片说明

邮递员请求(成功) 在此处输入图片说明

如果这是一个与快递相关的问题,这里是我的快递代码:

const express = require("express")
const bodyParser = require("body-parser")
const logger = require('morgan')
const api = require("./api/api")
const path = require('path')
const secret = require('./models/secrets')
const expressJWT = require('express-jwt')
const cors = require('cors');

const app = express()

app.set("json spaces", 2)
app.use(logger("dev"))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

app.use(expressJWT({secret: secret}).unless({path : ['/api/authenticate', '/api/register']}))

app.use("/api/", api)

app.use(function (req, res, next) {
  var err = new Error('Not Found')
  err.status = 404
  next(err)
})

app.use(function (err, req, res, next) {
  console.error(err.status)
  res.status(err.status || 500)
  res.json({ msg: err.message, status: err.status })
})

// Body Parser middleware
app.use(bodyParser.json());

// CORS middleware
app.use(cors());

// set static folder
app.use(express.static(path.join(__dirname, 'public')));
//Call this to initialize mongoose
function initMongoose(dbConnection) {
  require("./db/mongooseConnect")(dbConnection)
}

app.initMongoose = initMongoose

module.exports = app
Run Code Online (Sandbox Code Playgroud)

/authenticate的路由看起来像这样

// Authenticate
router.post('/authenticate', (req, res, next) => {
    const username = req.body.username;
    const password = req.body.password;

    User.getUserByUsername(username, (err, user) => {
        if (err) throw err;
        if (!user) {
            return res.json({ success: false, msg: 'User not found' });
        }

        User.comparePassword(password, user.password, (err, isMatch) => {
            if (err) throw err;
            if (isMatch) {
                const token = jwt.sign({data: user}, secret, {
                    expiresIn: 604800 // 1 week
                });

                res.json({
                    success: true,
                    token: 'Bearer ' + token,
                    user: {
                        id: user._id,
                        name: user.name,
                        username: user.username,
                        email: user.email
                    }
                });
            } else {
                return res.json({ success: false, msg: 'Wrong password' });
            }
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

Kir*_*kin 6

正在发出的请求称为预检请求- 您可以在错误消息中看到这一点,其中指出对预检请求的响应未通过访问控制检查。预检请求由浏览器发出,因为 CORS 只是浏览器安全限制 - 这就是它在 Postman 中工作的原因,当然,邮递员不是浏览器。

您正在使用的 CORS 中间件的文档说明如下:

要启用预飞行,您必须为要支持的路由添加新的 OPTIONS 处理程序:

在您的情况下,由于您已将 CORS 处理设置为适用于所有来源等,您可以使用以下内容(同样来自文档):

app.options('*', cors()) // include before other routes
Run Code Online (Sandbox Code Playgroud)

正如评论所述,您需要将其移至.js文件顶部,以便首先对其进行处理。

还建议专门设置允许的来源、路由等,以锁定哪些来源能够访问哪些端点。您可以使用自己喜欢的搜索引擎阅读更多相关信息。

  • 谢谢!我没有考虑,但顺序是问题。我移动了 app.use(cors()); 直到 expressJWT 中间件之前和 app.use("/api/", api) 之前。这最终解决了这个问题。不过,我不必添加“*”。 (2认同)