Express + Passport.js:req.user未定义 [英] Express + Passport.js: req.user is UNDEFINED

查看:73
本文介绍了Express + Passport.js:req.user未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Express API服务器和一个没有代理的create-react-app应用程序.我使用用于OAuth的Passport.js,该代码在MongoDB中用于反序列化用户.

I've got an express API server and separately a create-react-app app with no proxy. I use passport.js for OAuth, that looks in MongoDB to deserialize user.

在后端,我设置了cors中间件,在前端,我用服务器URL配置了axios基本URL.

In the backend, I setup cors middleware and in the frontend, I configured axios base URL with my server URL.

通过邮递员/手动在URL栏中写入端点,我的API请求成功,并且找到了req.user.但是,如果我使用axios从前端发出该API请求,则req.user是未定义的或为空字符串.

With postman/manually writing endpoint in the URL bar, my API request succeed and req.user was found. But if I make that API request from the frontend with axios, req.user is undefined or an empty string.

我不知道,请帮帮我.

middlewares.js

middlewares.js

  app.use(cors())

  app.use(cookieSession({
    maxAge: 30 * 24 * 60 * 60 * 1000,
    keys: [keys.cookieKey]
  }))

  app.use(compression())

  if (process.env.NODE_ENV !== 'production') {
    app.use(morgan('tiny'))
  }

  app.use(bodyParser.json())

  app.use(helmet())

  app.use(passport.initialize())
  app.use(passport.session())

authRoutes.js

authRoutes.js

  app.get(
    '/auth/current_user',
    (req, res) => {
      res.send(req.user)
      console.log(req.user) // UNDEFINED ONLY WITH AXIOS IN REACT APP
    }
  )

actions.js

actions.js

axios.defaults.baseURL = process.env.REACT_APP_API_URL

export const fetchUser = () => async dispatch => {
  const { data } = await axios.get('/auth/current_user')
  console.log('USER DATA: ')
  console.log(data === '') // TRUE
  dispatch({
    type: FETCH_USER,
    payload: data
  })
}

passport-config.js

passport-config.js

passport.serializeUser((user, done) => {
  done(null, user.id)
})

passport.deserializeUser((id, done) => {
  User.findById(id).then(user => {
    done(null, user)
  })
})

复制步骤:

在服务器上:npm运行start-dev

on server: npm run start-dev

当您使用google登录时,身份验证流向正确,但是(如您在网络" chrome devtools选项卡中看到的)"/auth/current_user" api请求具有response.data ==="

when you login with google, auth flow goes right but ( as you can see in "network" chrome devtools tab ) the '/auth/current_user' api request has response.data === ""

推荐答案

我认为我有解决方案.

后端

首先,您必须安装cors npm install --save cors ,然后粘贴此代码.

First of all you must install cors npm install --save cors, than paste this code.

import cors from 'cors'

app.use(cors({
  methods:['GET','POST'],
  credentials: true 
}))

前端

使用带有凭证和标头选项的axios:

Use axios with credentials and headers options:

const config = {
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json',
  },
};
axios.post('http://localhost:8000/routes/register', user, config);

我希望它能对您或其他人有所帮助.

I hope it will help you or someone else.

这篇关于Express + Passport.js:req.user未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆