expressjsHow do I use Express.js to fetch data?
Express.js is a web application framework for Node.js that enables developers to easily create web applications. It provides a simple and powerful API for fetching data from a server.
To use Express.js to fetch data, we can use the fetch
API. Here is an example code:
const express = require('express');
const app = express();
app.get('/data', (req, res) => {
fetch('http://example.com/data.json')
.then(response => response.json())
.then(data => res.json(data));
});
app.listen(3000);
This code will fetch data from http://example.com/data.json
and send it back as a response to the client.
The code consists of the following parts:
const express = require('express');
- This line imports the Express.js module.const app = express();
- This line creates an Express.js application.app.get('/data', (req, res) => { ... });
- This line defines a route for the application which will fetch data when the/data
URL is requested.fetch('http://example.com/data.json')
- This line fetches the data from the specified URL..then(response => response.json())
- This line parses the response as JSON..then(data => res.json(data))
- This line sends the parsed data as a response to the client.app.listen(3000);
- This line starts the server on port 3000.
For more information, please refer to the Express.js documentation.
More of Expressjs
- How do I find Express.js tutorials on YouTube?
- How can I use Express.js with TypeScript?
- How can I set up unit testing for an Express.js application?
- How do I manage user roles in Express.js?
- How do I render a template using Express.js?
- How do I use Express.js to patch a route?
- How do I get a parameter from an Express.js request?
- How can I use Express.js to prevent XSS attacks?
- How can I use Express.js to implement websockets in my application?
- How can I use Express.js to trace requests?
See more codes...