最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

使用Angular和Express的CORS

运维笔记admin13浏览0评论

使用Angular和Express的CORS

使用Angular和Express的CORS

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

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

来自控制台的错误消息。

邮差要求(成功)

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

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

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

        UserparePassword(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' });
            }
        });
    });
});
回答如下:

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

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

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

在您的情况下,当您设置CORS处理以适用于所有来源等时,您可以使用以下(再次,从文档):

app.options('*', cors()) // include before other routes

正如评论所述,您需要将其向上移动到.js文件的顶部,以便首先处理它。

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论