Javascript 尽管启用了CORS,但express js api访问控制上的CORS允许源站

Javascript 尽管启用了CORS,但express js api访问控制上的CORS允许源站,javascript,node.js,express,cors,Javascript,Node.js,Express,Cors,我使用ExpressJS在服务器上提供API,我有几个路由设置、post、get等,除了post路由之外,我所有的路由都工作正常。我已经通过CORS包和其他一些中间件启用了CORS,但仍然遇到CORS问题,我从example.com发出的请求将发送到compiler.example.com并返回CORS问题,我的中间件设置为: //需要软件包等。。。 应用程序使用(头盔()) app.use(cors()) app.use(expressSanitizer()) app.use(express.

我使用ExpressJS在服务器上提供API,我有几个路由设置、post、get等,除了post路由之外,我所有的路由都工作正常。我已经通过CORS包和其他一些中间件启用了CORS,但仍然遇到CORS问题,我从example.com发出的请求将发送到compiler.example.com并返回CORS问题,我的中间件设置为:

//需要软件包等。。。
应用程序使用(头盔())
app.use(cors())
app.use(expressSanitizer())
app.use(express.json())
应用程序使用(功能(请求、恢复、下一步){
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-request-With,content-type')
res.setHeader('Access-Control-Allow-Credentials',true)
//传递到中间件的下一层
下一个()
});
//接下来是路线
我的错误:

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

不知道我哪里出了问题。。。似乎只是影响了我的帖子。

我和你有同样的问题,我通过添加cors作为应用程序选项解决了它,如下所示:

app.options('*', 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);


}
以及在我的路线上添加COR,如下所示:

app.options('*', 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);


}

老实说,我不知道为什么它是这样工作的,而且不是像在任何地方指定的正常方式那样工作。

您的服务器在这两个域中的哪一个上运行?如果您都在https上运行,请尝试避免使用http。在同一台服务器上,前端和API上,API在前端所在域的子域上运行。“
http://example.com
“似乎没有在https上运行。您是说您发布代码的express应用程序服务于这两个域吗?将第一行从*更改为
req.headers.origin
,并将“true”作为字符串传递