【问题标题】:axios.get not returning dataaxios.get 不返回数据
【发布时间】:2020-02-15 14:23:30
【问题描述】:

我正在使用 react、express 和 passport 来管理身份验证流程。

我最近在 Heroku 中将前端和后端分成了两个应用程序,并且我正在尝试连接双方(在服务器文件夹中有客户端文件夹之前)。在本地测试时,我的后端在登录访问 http://localhost:5000/auth/current_user 后工作,但是当我使用 axios 并从我的 redux 操作中调用时,它不会返回任何响应。

这是我的前端代码:

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);
    }
  }
};

当我登录后端以查看是否有会话时,我得到{} 作为响应。有时,我会随机获得护照信息{ passport: { user: '5da9b04eb086af53103ec4e9' } }

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

来自 Chrome 的标题如下(没有任何响应...): Chrome headers

如果有人可以帮助我,那就太好了!

提前致谢!

【问题讨论】:

  • res 来了还是没来。
  • 我应该看哪里?如果我在后端登录 res,我确实会得到很大的响应(对不起,我在这方面很新……)
  • 在护照中,我尝试记录每一步(serializeUser,deserializeUser,...)并返回数据。 passport.use( new OAuth2CognitoStrategy( options, async (accessToken, refreshToken, profile, done) => { // console.log(profile); const existingUser = await User.findOne({ cognitoId: profile.sub }); // console.log("existingUser: ", existingUser); if (existingUser) { return done(null, existingUser); } const user = await new User({ cognitoId: profile.sub, email: profile.email }).save(); done(null, user); } )
  • 通过console.log(res.data)检查
  • 哦,好的。不,没有数据。我一直在尝试查看信息丢失的位置。在我的回调函数中记录 req 时,我看到对 session ` session: { user: '5da9b04eb086af53103ec4e9' } }` 和 req.user 的引用。可能是因为不同的域/子域吗? api.example.com 与 www.example.com?无论如何,我正在尝试 localhost 并且只更改端口。我在背面使用了cors。

标签: node.js express axios passport.js


【解决方案1】:

我终于找到了解决问题的方法......似乎这是一个 CORS 问题。我不是很清楚,但会研究它。

所以,部分解决方案就在这个答案中:Express + Passport.js: req.user is UNDEFINED

这样,cookie 就会出现在我的控制台日志中。为了充分发挥作用,我必须将源域添加到 cors。

总之,我在服务器端添加到我的 index.js 中:

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

这个配置到我的 axios 得到:

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

【讨论】:

    【解决方案2】:

    您可以像这样使用 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 */
    

    【讨论】:

    • 是的,我使用的是 cors,但我还必须添加凭据设置。谢谢!
    猜你喜欢
    • 2021-12-13
    • 2020-04-11
    • 2019-02-10
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    相关资源
    最近更新 更多