繁体   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