简体   繁体   中英

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

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:

在此处输入图片说明

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

您需要在console.log之前调用await response.text()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM