Axios data coming out to be undefined

与世无争的帅哥 提交于 2019-12-11 15:56:49

问题


I have a route in nodeJs which looks like this

app.get("/", (req, res) => {
  console.log(req.user)
 res.json(req.user)
})

Here console.log showing undefined but if I visit the address (localhost:3000/)

it displays the following the data (in json)

// 20181025193337
// http://localhost:3000/

{
  "isFormFilled": false,
  "_id": "5bd1a3d82101d36407f81218",
  "username": "Rohit Bhatia",
  "userId": "102775073203963169965",
  "image": "https://lh5.googleusercontent.com/-7HxFRQOCd9Q/AAAAAAAAAAI/AAAAAAAAAU8/pgzBQd9X6pA/photo.jpg?sz=250",
  "__v": 0
}

Similarly from my react app, I making a axios request where response.data is coming out to be undefined (or "")

 componentWillMount() {
         axios.get("http://localhost:3000/").then(response => {
             console.log(response)
         }).catch(error => {
             console.log(error)
         })
    }

If I do something like this in my route

 app.get("/", (req, res) => {
      console.log(req.user)
     res.json("here)
    })

the data in my axios request is showing as "Here"

[Question:] Why could this be happening or what could I be doing wrong here?

Ps: I have enabled crocs resource sharing since I am making request locally


回答1:


You're console.logging req.user which isn't in your object, hence why it's undefined. console.log(req.userId) or console.log(req.username) and notice that it is defined



来源:https://stackoverflow.com/questions/52991355/axios-data-coming-out-to-be-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!