簡體   English   中英

當我部署我的網站時,客戶端發布/獲取請求被 CORS 阻止

[英]When I deploy my website, client post/get requests blocked by CORS

使用 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}))

在我的前端網站控制台中,我收到此錯誤:CORS policy: Response to preflight request未通過訪問控制檢查:請求的資源上不存在“Access-Control-Allow-Origin”header。

有任何想法嗎?

You have to implement one to two things For backend use node package for CORS 'npm install cors' and add this to your App configuration 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

另外,建議使用異步配置 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')
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM