expressjsHow can I use Express.js to make an XHR request?
Express.js is a web application framework for Node.js that provides a robust set of features for web and mobile applications. It is also widely used for making XHR (XMLHttpRequest) requests. To make an XHR request using Express.js, you can use the built-in request
module.
Example code
const express = require('express');
const request = require('request');
const app = express();
app.get('/', (req, res) => {
request('https://example.com', (error, response, body) => {
if (!error && response.statusCode == 200) {
res.send(body);
}
});
});
app.listen(3000);
The example code above creates an Express.js server which listens on port 3000, and makes an XHR request to https://example.com
when a user visits the root URL. The response body is then sent back to the user.
The code can be broken down into the following parts:
const express = require('express');
- This line imports the Express.js module.const request = require('request');
- This line imports therequest
module, which is used for making XHR requests.const app = express();
- This line creates an Express.js application.app.get('/', (req, res) => {
- This line creates a route handler for the root URL.request('https://example.com', (error, response, body) => {
- This line makes an XHR request tohttps://example.com
.if (!error && response.statusCode == 200) {
- This line checks if the request was successful.res.send(body);
- This line sends the response back to the user.
For more information, see the Express.js documentation and the Request documentation.
Note: The example code provided is for demonstration purposes only and should not be used in production.
More of Expressjs
- How can I use express-zip js to zip and download files?
- How do I find Express.js tutorials on YouTube?
- How do I use Express.js to create a cluster?
- How can I use Express.js and Vite together for software development?
- How do I set the time zone in Express.js?
- How do I use adm-zip with Express.js?
- How do I set up a YAML configuration file for a Node.js Express application?
- How do I download a zip file using Express.js?
- How can I use Zipkin to trace requests in Express.js?
- How do I use Zod with Express.js?
See more codes...