【问题标题】:Error while making a request from React server to node Server从 React 服务器向节点服务器发出请求时出错
【发布时间】:2019-09-08 19:40:38
【问题描述】:

嘿,伙计们,我正在制作一个 MERN 堆栈项目,所以我面临的问题是,在来自 react 服务器的操作创建者中,我必须向节点 js 服务器发出 get 请求,或者简而言之

来自http://localhost:3000/我必须向http://localhost:5000/api/currentuser中的数据提出请求

nodejs服务器中存储的数据是{"_id":"5d73fd9003b5302f6b013a46","googleid":"109463598810933991924","__v":0} 这是从 mongodb 中获取的

所以我所做的是在我的动作创建器文件中

我喜欢

import axios from "axios";
export const fetchuser = () => {
    return async(dispatch)=>{
       const res=await axios.get("http://localhost:5000/api/currentuser")
            dispatch({
                type:'fetchuser',
                payload:res.data

        })

    }

};

但后来在我的控制台中我遇到了错误,它说

Access to XMLHttpRequest at 'http://localhost:5000/api/currentuser' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

【问题讨论】:

标签: node.js reactjs redux


【解决方案1】:

没有 Express 代码很难有信心,但您可能需要配置 Express 服务器以设置 CORS。

您可以在此处查看 Express + CORS 的文档:https://expressjs.com/en/resources/middleware/cors.html

var express = require("express");
var cors = require("cors");
var app = express();

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

有关 CORS 的更多详细信息,read this

【讨论】:

  • 嘿,但我没有取回我的数据,我的意思是当我在浏览器中转到 localhost:5000/api/currentuser 时,我得到了回复,但是在通过 axios 发出 get 请求后,我的数据是一个空字符串数据: " "
  • 您仍然收到blocked by CORS policy 错误吗?
  • 如果你想看看github.com/ratnabh/node-with-react,请创建一个 github repo
【解决方案2】:

这是跨域问题。您尚未在 nodejs 中提供对 http://localhost:3000/ 的访问权限。

有两种简单的方法,

1.没有任何 npm 包的简单方法

app.use(function (req, res, next) {

    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');

    // methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    / headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    next();
});

2。使用 cors npm 包:

官方文档网址 https://expressjs.com/en/resources/middleware/cors.html

-允许所有域/url

import cors from 'cors';
app.use(cors());

您会注意到新的标头被返回为 访问控制允许来源:*

-允许特定的域/url,

import cors from 'cors';

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

标题将是,

访问控制允许来源:http://localhost:3000

【讨论】:

  • 嘿,但我没有取回我的数据,我的意思是当我在浏览器中转到 localhost:5000/api/currentuser 时,我得到了回复,但是在通过 axios 发出 get 请求后,我的数据是一个空字符串数据: " "
  • 您能分享我的逻辑示例代码吗?所以我可以帮你找到解决办法。
  • req.user 中没有任何内容。 router.get('/api/currentuser',(req,res,next)=>{ res.send(req.user) })
  • Nodejs 路由尝试 console.log(req.user);看看里面有没有东西。
  • 嘿 nikhil 好吧,我不确定你是否尝试过这个,但首先你必须去路线 localhost:5000/auth/google 然后你将在 localhost:5000/ 上登录谷歌帐户api/currentuser 在浏览器中手动获取详细信息
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-27
  • 1970-01-01
相关资源
最近更新 更多