Axios data coming out to be undefined

2019-09-02 14:28发布

问题:

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