expressjsHow can I make an XHR request using Express.js?
An XHR request can be made using Express.js by using the express.json()
middleware. This middleware will parse the body of the request and make it available in the req.body
object.
Example code
const express = require('express');
const app = express();
// Parse request body as JSON
app.use(express.json());
// Make an XHR request
app.post('/data', (req, res) => {
// req.body will contain the parsed JSON data
console.log(req.body);
res.send('Success!');
});
app.listen(3000);
Output example
Success!
The code consists of the following parts:
const express = require('express')
- imports theexpress
moduleconst app = express()
- creates an instance of an Express applicationapp.use(express.json())
- adds theexpress.json()
middleware to the application, which will parse the body of the request as JSONapp.post('/data', (req, res) => {...})
- adds a POST endpoint to the application, which will be called when an XHR request is made to the/data
endpointconsole.log(req.body)
- logs the parsed JSON data from the request body to the consoleres.send('Success!')
- sends a response back to the client
Helpful links
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 can I use Express.js to compress my files?
- How do I use Express.js to create and manage API keys?
- How do I set the time zone in Express.js?
- How do I set up a YAML configuration file for a Node.js Express application?
- How can I use Express.js and Nest.js together to create a web application?
- How do I use adm-zip with Express.js?
- How do I download a zip file using Express.js?
- How do I use Yarn to add Express.js to my project?
See more codes...