简体   繁体   English

axios.get 不返回数据

[英]axios.get not returning data

I'm using react, express and passport to manage the auth flow.我正在使用 react、express 和 passport 来管理身份验证流程。

I recently separated the frontend and the backend into two apps in Heroku, and I'm trying to connect both sides (before I had the a client folder inside the server folder).我最近将前端和后端分为 Heroku 中的两个应用程序,并且我正在尝试连接双方(在服务器文件夹中有客户端文件夹之前)。 When testing locally, my backend works after login accessing to http://localhost:5000/auth/current_user , but when I use axios and call from my redux action it doesn't return any response.在本地测试时,我的后端在登录访问http://localhost:5000/auth/current_user后工作,但是当我使用 axios 并从我的 Z7490FE17CAEC373F22909D65B6E20E 调用时它不会返回任何响应。

This is my code from the front side:这是我前面的代码:

export const fetchUser = () => async dispatch => {
  try {
    const res = await axios.get(
      process.env.REACT_APP_API_URL + "/auth/current_user"
    );
    console.log("fetchUser: ", res);
    dispatch({ type: FETCH_USER, payload: res.data });
  } catch (e) {
    if (e.response) {
      console.log("fetchUser:", e.response);
    }
  }
};

When I log my backend side to see if there's a session, I get {} as response.当我登录后端以查看是否有 session 时,我得到{}作为响应。 Sometimes, randomly I do get the passport info { passport: { user: '5da9b04eb086af53103ec4e9' } }有时,我会随机获得护照信息{ passport: { user: '5da9b04eb086af53103ec4e9' } }

  app.get("/auth/current_user", (req, res) => {
    console.log(req.session);
    res.send(req.user);
  });

Headers from Chrome are the following (without any response...): Chrome headers Chrome 的标头如下(没有任何响应...): Chrome 标头

Would be great if someone can help me out!如果有人可以帮助我,那就太好了!

Thanks in advance!提前致谢!

I've finally found a solution to the problem... Seems like it was a CORS problem.我终于找到了解决问题的方法......似乎这是一个 CORS 问题。 I don't really understand it clearly, but will study it.我不是很清楚,但会研究它。

So, partially, the solution was in this answer: Express + Passport.js: req.user is UNDEFINED因此,部分解决方案在这个答案中: Express + Passport.js: req.user is UNDEFINED

With this, the cookies appeared in my console log at the front side.有了这个,cookies 出现在我前面的控制台日志中。 To fully work, I had to add the origin domain to the cors.为了充分发挥作用,我必须将源域添加到 cors。

In conclusion, I added to my index.js at the server side:总之,我在服务器端添加到我的 index.js 中:

app.use(
  cors({
    methods: ["GET", "POST"],
    credentials: true,
    origin: "http://localhost:3000"
  })
);

And this config to my axios get:这个配置到我的 axios 得到:

    const config = {
      withCredentials: true,
      headers: {
        "Content-Type": "application/json"
      }
    };

Instead of all this, you can use cors npm like this.代替所有这些,您可以像这样使用 cors npm。

npm install --save cors

var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
/* your regular routes go here */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM