Home > Mobile >  Node.js and express.js how to read 'get' endpoint?
Node.js and express.js how to read 'get' endpoint?

Time:11-05

I am trying to pass simple data from my server to a javascript file called on another html page. I am testing sending a single string from the server, but am not sure how to receive it. Server below:

const express = require('express')
const app = express()
const port = 3000

app.use(express.static("./assets"));

app.get('/', (req, res) => {
  //res.send('Hello World!')
  res.sendFile('./main.html', { root: __dirname });
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

app.get('/get-test', async (_req, res) => {
    try {
        const test_string = "get-test request string";
        return res.send(test_string);
    } catch (e) { throw e; }
});

And in another javascript file I have the following:

async function testing() {
    const response = await fetch('/get-test');
    console.log(response);
}
testing();

The console.log gives me a whole object, and clicking through it I can't seem to find my test_string anywhere:

enter image description here

So I believe the get request worked, but how do I actually access the data inside that I want?

CodePudding user response:

You need to call await response.text() before console.loging it.

CodePudding user response:

So in this functio:

async function testing() {
    const response = await fetch('/get-test');
    console.log(response);
}
testing();

You will need to put await inside the console.log

so like this:

async function testing() {
    const response = await fetch('/get-test');
    console.log(await response);
}
testing();

Why ?

Since javascript is asynchronous when retrieving data there will be a delay. That is why they implemented async / await and promises. So when you trying to make a get request with fetch you will need need to await the response. But the response is also a promise, which mean you will need to await the response aswell. This makes more sense, when you try to process the response to lets say json.

A little tip

When the console.log returns no error, but no data either. It might because of a promise issue

  • Related