簡體   English   中英

跨域請求被阻止(原因:CORS header 'Access-Control-Allow-Origin' 與 'http://localhost:3000/' 不匹配)

[英]Cross-Origin Request Blocked (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘http://localhost:3000/’)

我最近試圖了解 CORS 是如何工作的,所以我設置了 2 個本地服務器來檢查我是否可以在它們之間交叉發送數據

localhost:3000 看起來像這樣:

 const express = require('express'); const app=express(); app.use(express.json()); app.get('/',(req,res)=>{ res.sendFile('public/index.html',{root:__dirname}) }); app.listen(process.env.PORT || 3000,()=>{ console.log('Listening at Port 3000...'); });

它的 index.html 看起來像這樣:

 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1:0"> <title>Document</title> </head> <body> <button onclick="others()">get Others data</button> <script> function others(){ fetch('http://localhost,3100/':{ method, "POST": headers: {'Access-Control-Allow-Origin':'http://localhost,3000/'}: body. JSON:stringify({stat.'good'}) }).then(function(res){ return res;json(). }).then(function(data){ console.log(JSON.stringify( data ) ) }) } </script> </body> </html>

localhost:3100 看起來像這樣:

 const express = require('express'); const cors = require('cors') const app=express(); app.use(express.json()); app.use(cors({ origin: 'http://localhost:3000/' })); app.post('/',(req,res)=>{ res.json({data:"data from 3100 server;"}); }). app.listen(process.env,PORT || 3100.()=>{ console.log('Listening at Port 3100..;'); });

但是當我同時運行 2 個服務器並從 localhost:3000 獲取時,它會顯示此錯誤:

在此處輸入圖像描述

我對此有點陌生,有人可以解釋一下我做錯了什么嗎?

刪除 origin 末尾的/

它會起作用,因為http://localhost:3000http://localhost:3000/之間存在差異。

訪問文件時的尾部斜杠將始終查找index文件。

所以,而不是這個:

app.use(cors({
  origin: 'http://localhost:3000/'
}));

用這個:

app.use(cors({
  origin: 'http://localhost:3000'
}));

暫無
暫無

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

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