简体   繁体   English

Expressjs如何仅在一条路线上启用CORS?

[英]Expressjs How to enable CORS on just one route?

The code below does not work 下面的代码不起作用

app.post('/blah', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, HEAD');
    res.status(204).send();
});

Note that I don't want turn on CORS for the whole app. 请注意,我不想为整个应用程序打开CORS。

Posting this as an answer since it turned out to be the issue (per my earlier comment). 将其发布为答案,因为原来是问题所在(根据我之前的评论)。 Depending upon the exact CORS request you are making, then browser may decide that it needs to do a pre-flight of the request. 根据您提出的确切CORS请求,浏览器可能会决定需要对请求进行预检。 If it does, then you also need to set the custom headers in a matching OPTIONS request. 如果是这样,那么您还需要在匹配的OPTIONS请求中设置自定义标头。

A number of things can trigger a pre-flight such as custom headers, certain verbs being used, certain auth mechanisms, etc... 许多事情可以触发预检,例如自定义标题,正在使用的某些动词,某些身份验证机制等。

There's a description of what types of requests trigger a pre-flight here in these articles: 这些文章中介绍了哪些类型的请求触发预检:

Using CORS 使用CORS

Cross Origin Resource Sharing 跨源资源共享

Basically, it's any request that isn't defined as a "simple request" where simple requests only use GET, HEAD and POST and only a small set of custom headers. 基本上,这是任何未定义为“简单请求”的请求,其中简单请求仅使用GET,HEAD和POST,并且仅使用少量的自定义标头。 Anything else and even some values for certain headers will trigger a preflight request where the browser sends an OPTIONS request to the same URL request pre-flight authorization before sending the actual URL. 任何其他内容,甚至某些标头的某些值,都会触发预检请求,其中浏览器在发送实际URL之前向相同的URL请求预检授权发送OPTIONS请求。

you can use something like this : 您可以使用这样的东西:

var express = require('express')
var cors = require('cors')
var  corsOptions = { origin: 'http://yourapp.com'}
var app = express()

app.get('/products/:id', cors(corsOptions), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a Single Route'})
})

app.listen(8080, function () {
  console.log('CORS-enabled web server listening on port 8080')
})

By default, only 6 response headers are exposed over CORS: 默认情况下,只有6个响应标头通过CORS公开:

  1. Cache-Control 缓存控制
  2. Content-Language 内容语言
  3. Content-Type 内容类型
  4. Expires 过期
  5. Last-Modified 上一次更改
  6. Pragma 语用

If you want to expose other headers, you can use the exposedHeaders option: 如果要公开其他标头,则可以使用暴露的标头选项:

 corsOptions = {
  exposedHeaders: ['Content-Length', 'X-Foo', 'X-Bar'],
}

Please refer this for more detail on CORS: 请参阅此以获取有关CORS的更多详细信息:

More detail on cors 关于cors的更多细节

What version of Express are you using? 您正在使用哪个版本的Express? v4 of the API exposes a set() method on res where you can define headers. API的v4在res上公开了set()方法,您可以在其中定义标头。 If passing multiple headers, you pass an object. 如果传递多个标头,则传递一个对象。 Try something like this: 尝试这样的事情:

res.set({
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, HEAD'
});

Documentation . 文件资料

Building on Clark Jung's reply, you can use https://github.com/expressjs/cors#enable-cors-for-a-single-route 基于Clark Jung的回复,您可以使用https://github.com/expressjs/cors#enable-cors-for-a-single-route

var express = require('express')
var cors = require('cors')
var app = express()

app.get('/products/:id', cors(), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a Single Route'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

Why don't you use https://github.com/expressjs/cors . 为什么不使用https://github.com/expressjs/cors You can just use like this. 您可以像这样使用。

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

Or refer to here https://enable-cors.org/server_expressjs.html 或参考这里https://enable-cors.org/server_expressjs.html

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/', function(req, res, next) {
  // Handle the get for this route
});

app.post('/', function(req, res, next) {
 // Handle the post for this route
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM