简体   繁体   English

CORS政策如何在快递中妥善管理?

[英]How to manage CORS policy properly in express?

I am trying to allow access from everywhere.我试图允许从任何地方访问。

I have tried using app middleware:我试过使用应用程序中间件:

app.use(function (req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader('Access-Control-Allow-Methods', '*');
  res.setHeader("Access-Control-Allow-Headers", "*");
  next();
});

I have tried using it in the route:我试过在路线中使用它:

app.post('/login',function(req,res){
var login   = req.body;
var sess    = req.session;

if (!login.email && !login.pwd){    
    return res.status(401);
}
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Headers", '*');
.... more code here

Both do not work.两者都不起作用。 I keep getting an error: "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."我不断收到错误消息:“对预检请求的响应未通过访问控制检查:请求的资源上不存在‘Access-Control-Allow-Origin’header。”

Further down the server, we use similar code for another route, which works:在服务器的下方,我们对另一条路由使用类似的代码,该路由有效:

app.post('/questar',function(req,res){
//allow xhr post from retireup domains
var cors = {
    origin: "https://www.website.com";
};
res.header("Access-Control-Allow-Origin", cors.origin);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.type('application/json');

I cannot tell the difference between the code, but only one set works.我无法分辨代码之间的区别,但只有一组有效。 Any ideas why?任何想法为什么? This seems like an issue that shouldn't be so complicated.这似乎是一个不应该这么复杂的问题。 Thanks谢谢

After applying "cors" middleware.应用“cors”中间件后。 You should be passed "http://" before "localhost:".您应该在“localhost:”之前传递“http://”。 in url send to by Axios like this:在由 Axios 发送的 url 中,如下所示:

axios.get("http://localhost:8080/api/getData")
.then(function (response) {
this.items= response.data;
}).catch(function (error) {
console.log(error)
});

MDN has a very short explanation on how a server should respond to a Preflight Request . MDN对服务器应该如何响应Preflight Request有一个非常简短的解释。

You handle CORS preflight requests by handling the HTTP OPTIONS method (just like you would handle GET and POST methods) before handling other request methods on the same route:处理同一路由上的其他请求方法之前,您可以通过处理 HTTP OPTIONS 方法(就像处理 GET 和 POST 方法一样)来处理 CORS 预检请求:

app.options('/login', ...);
app.get('/login'. ...);
app.post('/login'. ...);

In your case, it might be as simple as changing your app.use() call to app.options() , passing the route as the first argument, setting the appropriate headers, then ending the response:在你的情况下,它可能是那样简单改变你app.use()调用app.options()传递路线作为第一个参数,设置适当的标题,然后结束了回应:

app.options('/login', function (req, res) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader('Access-Control-Allow-Methods', '*');
  res.setHeader("Access-Control-Allow-Headers", "*");
  res.end();
});
app.post('/login', function (req, res) {
  ...
});

Configure the CORS stuff before your routes, not inside them.在你的路由之前配置 CORS 的东西,而不是在它们里面。

Here, like this (from enable-cors.org ):在这里,像这样(来自enable-cors.org ):

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

I always configure it like this in my Express+Angular apps and it works just fine.我总是在我的 Express+Angular 应用程序中这样配置它,它工作得很好。

Hope it helps.希望能帮助到你。

First install, the "cors" package from npm: npm i -S cors首先安装,来自 npm 的“cors”包: npm i -S cors

Then enable it in your express server.然后在您的快速服务器中启用它。

var express = require('express'),
  cors = require('cors');

const app = express();
app.use(cors());

...

Following other's answers, this worked for me:按照其他人的答案,这对我有用:

res.setHeader("Access-Control-Allow-Origin", 'http://myDomain:8080');
res.setHeader('Access-Control-Allow-Methods', 'POST,GET,OPTIONS,PUT,DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Accept');

Following some standard node projects out there, below CORS configuration worked for me always.遵循一些标准节点项目,下面的 CORS 配置总是对我有用。 It requires the npm package 'cors'.它需要 npm 包“cors”。 Note: Origin * means enabling responses to any origin and replies with status code 200. If this needs to be limited to one domain, update the origin accordingly.注意: Origin * 表示启用对任何来源的响应,并使用状态代码 200 进行回复。如果需要将其限制为一个域,请相应地更新来源。 Ex: [origin: ' http://exampleui.com ']例如:[来源:' http : //exampleui.com ']

var cors = require('cors');
var corsOptions = {
    origin: '*',
    optionsSuccessStatus: 200,
  }
app.use(cors(corsOptions));
app.use(express.json())

All you have to whitelist the domains name to avoid getting cors error messages.您只需将域名列入白名单,以避免收到 cors 错误消息。

There is a plugin called cors , installed it into your project using this command有一个名为cors的插件,使用此命令将其安装到您的项目中

npm i cors

after installing use this code to remove the cors related errors form your project.安装后使用此代码从项目中删除 cors 相关错误。

const cors = require('cors');

const corsOption = {
    credentials: true,
    origin: ['http://localhost:3000', 'http://localhost:80']
}

app.use(cors(corsOption));

In the origin section you can pass any domain to whitelist it.origin部分,您可以传递任何域以将其列入白名单。 If you want to whitelist all the domain names, instead of passing the the urls array.如果要将所有域名列入白名单,而不是传递 urls 数组。 you can pass '*' over there.你可以在那边传递'*'

Example: origin: '*'示例: origin: '*'

credentials: Configures the Access-Control-Allow-Credentials CORS header. Set to true to pass the header, otherwise it is omitted. credentials:配置Access-Control-Allow-Credentials CORS header。设置为true表示通过header,否则省略。

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

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