【发布时间】:2021-08-11 11:27:49
【问题描述】:
我最近想了解 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 获取时,它会显示此错误:
我对此有点陌生,有人可以解释一下我做错了什么吗?
【问题讨论】:
标签: javascript node.js json express cors