【问题标题】:Cross-Origin Request Blocked (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘http://localhost:3000/’)跨域请求被阻止(原因:CORS 标头“Access-Control-Allow-Origin”与“http://localhost:3000/”不匹配)
【发布时间】: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


    【解决方案1】:

    删除原点末尾的/

    它会起作用,因为http://localhost:3000http://localhost:3000/ 之间存在差异。

    访问文件时的尾部斜杠将始终查找index 文件。

    所以,不要这样:

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

    使用这个:

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

    【讨论】:

    • 另外,你可能想在其中添加http://127.0.0.1:3000,因为如果你的服务器正在设置cookie,那么http://localhost:3000 is not equal to 127.0.0.1:300```
    • 天哪,就这么简单吗?非常感谢你
    猜你喜欢
    • 2016-12-21
    • 2016-04-02
    • 1970-01-01
    • 2019-11-13
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    相关资源
    最近更新 更多