javascript - 跨域请求被阻止(原因:CORS 标头“Access-Control-Allow-Origin”与“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:3000
它会起作用,因为和之间存在差异http://localhost:3000/
。
访问文件时的尾部斜杠将始终查找index
文件。
所以,而不是这个:
app.use(cors({
origin: 'http://localhost:3000/'
}));
用这个:
app.use(cors({
origin: 'http://localhost:3000'
}));
推荐阅读
- c++ - 程序如何“记住”临时对象?
- javascript - 如何删除默认变体选项并具有空单选按钮
- python - python MNIST 数据集“无属性 train_images”
- python - 在 OSX 上的 python3 中使用 Path.glob 查找带有 unicode 字符的文件
- python - 与浏览器不同的无头 Chrome 页面源
- pandas - 在不手动计算子图数量的情况下创建 matplotlib 子图?
- modal-dialog - 从模态视图提交后更新移动设备中的 Slack 主页选项卡 (views.publish)
- google-chrome-extension - Chrome 扩展无法在 Chrome 网上应用店开发者仪表板中上传
- python - 如何使用 scipy.stats 中的 multivariate_normal.cdf 函数始终获得相同的结果?
- sql - 解析雪花中的json键值,其中键中有一个点