Categories
JavaScript Answers

How to add basic Ajax send/receive with Node.js?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.