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/dataURL 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 can I disable the X-Powered-By header in Express.js?
- How do I write unit tests for ExpressJS?
- How do I use Yarn to add Express.js to my project?
- How do I create a tutorial using Express.js?
- How do I set a header using Express.js?
- What is Express.js?
- What are some of the best alternatives to Express.js for web development?
- How do I use Express.js to create a YouTube clone?
- How do I use Express.js to parse YAML files?
- How do I implement CSRF protection in an Express.js application?
See more codes...