To add basic Ajax send/receive with Node.js, we can use Express and fetch.
For instance, we write
const app = require("express").createServer();
app.get("/string", (req, res) => {
const strings = ["foo", "bar", "baz"];
const n = Math.floor(Math.random() * strings.length);
res.send(strings[n]);
});
app.listen(8001);
to add the get /string route which returns a random string from the strings
array as the response body with res.send
.
Then we write
const res = await fetch("/string");
const string = await res.text();
to make a get request to /string with fetch
.
And get the response body with res.text
.