首页 > 解决方案 > 跨域请求被阻止(原因: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 获取时,它会显示此错误:

在此处输入图像描述

我对此有点陌生,有人可以解释一下我做错了什么吗?

标签: javascriptnode.jsjsonexpresscors

解决方案


删除/origin 末尾的

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

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

所以,而不是这个:

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

用这个:

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

推荐阅读