简体   繁体   English

Express.js CORS 配置,PUT 不行?

[英]Express.js CORS configuration, PUT does not work?

I have a React application and Nodejs(Express) in the Backend.我在后端有一个 React 应用程序和 Nodejs(Express)。 After deploying to the host server, The function I did for updating some documents stop working properly.部署到主机服务器后,我为更新某些文档所做的功能停止正常工作。 It gives the CORS error:它给出了 CORS 错误:

在此处输入图片说明

I have this line of code to handle CORS policy in my server.js:我有这行代码来处理 server.js 中的 CORS 策略:

app.use((req, res, next) => {
  res.set({"Access-Control-Allow-Origin" : "*", 
           "Access-Control-Allow-Methods" : "HEAD, OPTIONS, GET, POST, PUT, PATCH, DELETE", 
           "Access-Control-Allow-Headers" : "Content-Type, Authorization, X-Requested-With"})
  next();
});

It is ok for GET and POST methods but does not work for PUT (Don't know if Delete works haven't tried) GET 和 POST 方法可以,但对 PUT 不起作用(不知道 Delete 是否有效没试过)

I am on this issue for plenty of time;我在这个问题上有很多时间; tried this: https://stackoverflow.com/a/42463858/11896129试过这个: https : //stackoverflow.com/a/42463858/11896129

looked for a bunch of solutions on the net, tried to configure it from IIS web.config file, nothing resolve my problem.在网上寻找了一堆解决方案,尝试从 IIS web.config 文件配置它,但没有解决我的问题。 Which part may I miss?我可能会错过哪个部分?

As stated on MDN:MDN 所述:

Additionally, for HTTP request methods that can cause side-effects on server's data (in particular, for HTTP methods other than GET, or for POST usage with certain MIME types ), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method.此外,对于可能对服务器数据产生副作用的 HTTP 请求方法(特别是对于GET 以外的HTTP 方法,或者对于某些 MIME 类型的 POST 使用),规范要求浏览器“预检”请求,请求支持的方法使用 HTTP OPTIONS 请求方法从服务器发送,然后在服务器“批准”后,使用实际 HTTP 请求方法发送实际请求。

So you do have to answer preflight requests:所以你必须回答预检请求:

  app.options("*", (req, res) => {
    res.status(200).send("Preflight request allowed");
  });

Read more about preflight requests here . 在此处阅读有关预检请求的更多信息。

This should work, I used this CORS configuration这应该有效,我使用了这个 CORS 配置

  app.use(function(req,res,next){
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, PATCH");
    res.header("Access-Control-Allow-Headers", "Accept, Content-Type, Authorization, X-Requested-With");

    next();
  });

Most likely the error No 'Access-Control-Allow-Origin' header is present that you see is coming from the preflight OPTIONS request, which is most likely not even reaching your express backend but is being hanlded by webserver in the front.您看到的错误No 'Access-Control-Allow-Origin' header is present很可能来自预检选项请求,该请求很可能甚至没有到达您的快速后端,而是由前端的网络服务器处理。

Either arrange for OPTIONS requests also to be relayed to your express backend in your webserver configuration or instruct the webserver to respond to it with required headers.要么安排 OPTIONS 请求也中继到您的网络服务器配置中的快速后端,要么指示网络服务器使用所需的标头对其进行响应。

Check these:检查这些:

https://support.plesk.com/hc/en-us/articles/115001338265-How-to-set-up-CORS-cross-origin-resource-sharing-in-Plesk-for-Linux- https://support.plesk.com/hc/en-us/articles/115001338265-How-to-set-up-CORS-cross-origin-resource-sharing-in-Plesk-for-Linux-

https://support.plesk.com/hc/en-us/articles/360005431913-Is-it-possible-to-enable-CORS-cross-origin-resource-sharing-on-Plesk-for-Windows https://support.plesk.com/hc/en-us/articles/360005431913-Is-it-possible-to-enable-CORS-cross-origin-resource-sharing-on-Plesk-for-Windows

https://talk.plesk.com/threads/iis-cors-configuration-problem-for-node-js-backend.355677/ https://talk.plesk.com/threads/iis-cors-configuration-problem-for-node-js-backend.355677/

You can use npm package cors ( https://www.npmjs.com/package/cors ) in your project.您可以在项目中使用 npm 包 cors ( https://www.npmjs.com/package/cors )。 Install it and then configure it as a middleware.安装它,然后将其配置为中间件。 And put it before your application routes.并将其放在您的应用程序路由之前。

 const cors = require("cors");

    const corsOptions = {   origin: "*",   methods:
    "GET,HEAD,PUT,PATCH,POST,DELETE",   allowedHeaders:
        "Access-Control-Allow-Headers,Access-Control-Allow-Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Origin,Cache-Control,Content-Type,X-Token,X-Refresh-Token",   credentials: true,   preflightContinue: false,  
    optionsSuccessStatus: 204 };

    app.use(cors(corsOptions));

Please try with below configuration请尝试以下配置

const cors = require('cors');
app.use(cors())

Please let me know if works for you or not.请让我知道是否适合您。

See the Github repo for more info: https://github.com/expressjs/cors有关更多信息,请参阅 Github 存储库: https : //github.com/expressjs/cors

We can use npm package to enable this too我们也可以使用 npm 包来启用它

npm install --save cors

After package is in place, use it as middleware as follows.包到位后,将其用作中间件,如下所示。

var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());

If you have requirement to confine your resource access to single application, that can be done as following如果您需要将资源访问限制在单个应用程序中,可以按以下方式完成

app.use(cors({
  origin: 'http://yourapp.com'
}));

If you have requirement to add access to multiple applications, that can be done as follows如果您需要添加对多个应用程序的访问权限,可以按如下方式完成

var allowedOrigins = ['http://localhost:3000',
                      'http://yourapp.com'];
app.use(cors({
  origin: function(origin, callback){
    // allow requests with no origin 
    // (like mobile apps or curl requests)
    if(!origin) return callback(null, true);
    if(allowedOrigins.indexOf(origin) === -1){
      var msg = 'The CORS policy for this site does not ' +
                'allow access from the specified Origin.';
      return callback(new Error(msg), false);
    }
    return callback(null, true);
  }
}));

Did you write middleware that attaches header before the line of code that handles PUT request?您是否编写了在处理 PUT 请求的代码行之前附加标头的中间件? I have a similar code but it worked for me.我有一个类似的代码,但它对我有用。 Another approach is to use npm 'cors' module.另一种方法是使用 npm 'cors' 模块。

For testing purpose, you can attach below test (you can attach the specific headers/methods later):出于测试目的,您可以附加以下测试(您可以稍后附加特定的标头/方法):

res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', '*');
res.header('Access-Control-Allow-Methods', '*');

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

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