提问者:小点点

express js api上的CORS access-control-allow-origin(尽管启用了CORS)


我使用Express JS在服务器上服务API,我有几条路由设置,post,get等,我的所有路由都运行良好,除了post路由。 我已经通过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

不知道我哪里出错了。。。 只是好像影响了我的职位。


共1个答案

匿名用户

您可以通过如下方式更改代码来完成所需的操作:res.setheader('access-control-allow-origin','*:*')并且如果您使用express应用程序,CORs问题正在发生,因为您的服务器没有监听相同的源。 所以您也可以这样做:app.listen(“something”); 服务器(app)

请分享您的整个服务器端代码,如果您想要更多的细节。