How to set cookies express, react.js

后端 未结 2 1851
迷失自我
迷失自我 2021-01-13 13:22

I am building a login system using express for node.js and react.js. In my back-end when a user logs in, it creates a cookie. When I go to Network > Login I can see this:

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-13 13:50

    Try to set on you index.js or app.js server side this:

      app.use(function(req, res, next) {
      res.header('Content-Type', 'application/json;charset=UTF-8')
      res.header('Access-Control-Allow-Credentials', true)
      res.header(
        'Access-Control-Allow-Headers',
        'Origin, X-Requested-With, Content-Type, Accept'
      )
      next()
    })
    

    and in you client site add options like this:

    let axiosConfig = {
      withCredentials: true,
    }
    
    export async function loginUser(data) {
      try {
        const res = await axios.post(
          `${URL}:${PORT}/${API}/signin`,
          data,
          axiosConfig
        )
        return res
      } catch (error) {
        console.log(error)
      }
    }
    

提交回复
热议问题