Languages
[Edit]
EN

Node.js / Express.js - AJAX GET request

3 points
Created by:
trincot
300

In this article, we would like to show you how to make AJAX GET requests in Express.js

1. Express.js GET methods example

In this section, we use Express.js to handle GET requests.

Note: it is required to add external library to run below example, so use:

npm install express

index.js file:

const express = require('express');

const port = 3000;
const app = express();

app.get('/examples/echo', (request, response) => {
    const text = request.query.text;
    response.send(text);
});

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

To run the server use: 

node index.js

Output:

server is listening at http://localhost:3000

2. Pure JavaScript (Vanilla JS) AJAX GET request

The following is an example execution of a fetch method that sends GET requests.

// ONLINE-RUNNER:browser;

<!DOCTYPE html>
<html>
  <body>
    <script>

      fetch('/examples/echo?text=hello')
        .then(async (response) => {
          if (response.status == 200) {
            const text = await response.text();
            console.log(`Received data: ${text}`);
          } else {
            console.log(`Received error: status=${response.status}`);
          }
        })
        .catch((error) => {
          console.error(`Occured exception: ${error}`);
        });

    </script>
  </body>
</html>

Node.js / Express.js - AJAX requests

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join