【问题标题】:When I deploy my website, client post/get requests blocked by CORS当我部署我的网站时,客户端发布/获取被 CORS 阻止的请求
【发布时间】:2021-12-28 11:56:36
【问题描述】:

使用 NodeJS 作为后端,使用 React 作为前端。前端使用 axios 来做 post/get 请求。使用 localhost:5000 作为服务器,使用 localhost:3000 作为客户端,一切都在开发中运行良好。

但是,当我将服务器和客户端部署到网站时,它们无法工作。我已将各自的本地主机地址更改为网站的地址,但无济于事。以下是我设置后端代码的方式:

const server = express();
server.use(cors({origin: "https://frontendwebsitename.com", credentials: true}));

server.use(express.json());
server.use(express.urlencoded({extended:true}))

在我的前端网站控制台中,我收到此错误: 从源“https://frontendwebsitename.com”访问“https://backendwebsitename.herokuapp.com/fetchDefaultSearch”的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“访问” -Control-Allow-Origin' 标头存在于请求的资源上。

有什么想法吗?

【问题讨论】:

    标签: node.js reactjs axios cors access-control


    【解决方案1】:

    你必须实现一到两件事 对于 CORS 'npm install cors' 的后端使用节点包 并将其添加到您的应用程序配置中 https://expressjs.com/en/resources/middleware/cors.html

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

    现在您需要验证您是否为 CORS 启用了前端存储桶设置,如果是,那么如果不是,您也需要启用它。 https://docs.aws.amazon.com/AmazonS3/latest/userguide/ManageCorsUsing.html

    【讨论】:

      【解决方案2】:

      另外,建议使用异步配置 CORS

      var cors = require('cors')
      var app = express()
      
      var allowlist = ['http://example1.com', 'http://example2.com']
      var corsOptionsDelegate = function (req, callback) {
        var corsOptions;
        if (allowlist.indexOf(req.header('Origin')) !== -1) {
          corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
        } else {
          corsOptions = { origin: false } // disable CORS for this request
        }
        callback(null, corsOptions) // callback expects two parameters: error and options
      }
      
      app.get('/products/:id', cors(corsOptionsDelegate), function (req, res, next) {
        res.json({msg: 'This is CORS-enabled for an allowed domain.'})
      })
      
      app.listen(80, function () {
        console.log('CORS-enabled web server listening on port 80')
      })
      

      【讨论】:

        猜你喜欢
        • 2019-08-22
        • 2020-03-26
        • 2021-03-10
        • 1970-01-01
        • 2020-08-27
        • 1970-01-01
        • 2019-12-16
        • 2019-09-30
        • 1970-01-01
        相关资源
        最近更新 更多