【问题标题】:CORS on express js api Access-Control-Allow-Origin despite CORS enabled尽管启用了 CORS,但 express js api Access-Control-Allow-Origin 上的 CORS
【发布时间】:2020-07-23 06:22:58
【问题描述】:

我正在使用 Express JS 在服务器上提供 API,我设置了多个路由、发布、获取等,并且我的所有路由都运行良好,除了我的发布路由。我已经通过 Cors 包和一些额外的中间件启用了 CORS,但仍然遇到 CORS 问题,我来自 example.com 的请求将发送到 compiler.example.com 并返回一个 CORS 问题,我的中间件设置是:

// require packages etc...

app.use(helmet())
app.use(cors())
app.use(expressSanitizer())
app.use(express.json())

app.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)

  // Pass to next layer of middleware
  next()
});

// routes come next

我的错误:

Access to XMLHttpRequest at 'https://compiler.example.com/api/endpoint' from origin 'http://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

VM734:1 POST https://compiler.example/api/endpoint net::ERR_FAILED

不知道哪里出错了……似乎只是影响了我的 POST。

【问题讨论】:

  • 您的服务器在两个域中的哪个域上运行?
  • 尽量避免使用http
  • 两者都在https上运行,在同一台服务器上,前端和API,API运行在前端所在域的子域上。
  • "http://example.com" 似乎无法在 https 上运行。您是说您发布其代码的 express 应用程序确实服务于两个域?
  • 将第一行从 * 更改为 req.headers.origin 并将 "true" 作为字符串传递

标签: javascript node.js express cors


【解决方案1】:

我遇到了和你一样的问题,我通过添加 cors 作为应用程序选项解决了这个问题:

app.options('*', cors());

除了像这样在我的路线上添加 cors :

const cors = require('cors');
module.exports = (app) => {

    const notes = require('../controllers/note.controller.js');

    app.post('/notes', cors(), notes.create);

    app.get('/notes', cors(), notes.findAll);

    app.get('/notes/:noteId', cors(), notes.findOne);

    app.post('/notes/:noteId', cors(), notes.update);

    app.delete('/notes/:noteId', cors(), notes.delete);


}

老实说,我不明白为什么它会这样工作,也不能像所有地方指定的正常方式那样工作。

【讨论】:

    猜你喜欢
    • 2012-03-25
    • 2019-10-02
    • 2017-10-24
    • 2021-05-12
    • 2014-11-20
    • 2016-09-30
    • 2021-07-18
    • 2018-02-25
    • 2018-04-14
    相关资源
    最近更新 更多