-1

My code,I am new to Express.

app.get('/', (req, res) => {
   const name = req.query.name;
   const rank = req.query.rank;
   const headers = Object.entries(req.headers)
  .map(([key, value]) => `${key}: ${value}`);
  
res.json({ success: true, data : { name, rank } , headers : headers });
});

server = app.listen(3000);

const res = axios.get('http://localhost:3000?name=John Malone&rank=Captain');

console.log(res);

Terminal output

Promise { <pending> }

I changed my code,data output

  data: {
    success: true,
    data: { name: 'John Malone', rank: 'Captain' },
    headers: [
      'accept: application/json, text/plain, */*',
      'user-agent: axios/0.20.0',
      'host: localhost:3000',
      'connection: close'
    ]
  }
}

axios.get('http://localhost:3000?name=John Malone&rank=Captain')
   .then(function(data) {
      console.log(data.data.name); // Data response from server
   });

Shows undefined.

MikiBelavista
  • 2,470
  • 10
  • 48
  • 70
  • 2
    Because `axios.get()` returns a promise. So, when you `console.log()` it's return value, that's what you get - a promise. Use `.then()` or `await` to get the resolved value from that promise. – jfriend00 Oct 01 '20 at 10:13
  • 1
    Because axios.get returns a promise. – dwjohnston Oct 01 '20 at 10:14

1 Answers1

1

There is two parts here:

  • Server part is written by node (express) you do it right
  • Client part is request by axios

You get Promise because axios.get return a Promise (an async request). So in that case I guess you want to log data to console. You should do something like this:

axios.get('http://localhost:3000?name=John Malone&rank=Captain')
   .then(function(data) {
      console.log(data); // Data response from server
   });
mihnsen
  • 385
  • 3
  • 8