EN
Express.js - AJAX GET request
3 points
In this article, we would like to show you how to make AJAX GET requests in Express.js.
In this section, we use Express.js to handle GET requests.
index.js
file:
xxxxxxxxxx
1
const express = require('express'); // installation: npm install express
2
3
const port = 3000;
4
const app = express();
5
6
app.get('/examples/echo', (request, response) => {
7
const text = request.query.text;
8
response.send(text);
9
});
10
11
app.listen(port, () => {
12
console.log(`server is listening at http://localhost:${port}`);
13
});
To run the server use:
xxxxxxxxxx
1
node index.js
Output:
xxxxxxxxxx
1
server is listening at http://localhost:3000
The following is an example execution of a fetch
method that sends GET requests.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<script>
5
6
fetch('/examples/echo?text=hello')
7
.then(async (response) => {
8
if (response.status == 200) {
9
const text = await response.text();
10
console.log(`Received data: ${text}`);
11
} else {
12
console.log(`Received error: status=${response.status}`);
13
}
14
})
15
.catch((error) => {
16
console.error(`Occured exception: ${error}`);
17
});
18
19
</script>
20
</body>
21
</html>
22