expressjsHow can I use Express.js to return a JSON response?
Express.js is a web application framework for Node.js that provides a simple way to return a JSON response. To use Express.js to return a JSON response, you need to set up your server, create a route to handle the request, and send the response in JSON format.
For example:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send({
message: 'Hello World!'
});
});
app.listen(3000);
The above code will create a server and listen on port 3000. When a request is sent to the / path, the server will respond with a JSON object containing a message.
The code consists of the following parts:
const express = require('express');- This imports the Express.js library.const app = express();- This creates an Express.js application.app.get('/', (req, res) => { ... });- This creates a route that will handle requests sent to the/path.res.send({ ... });- This sends a JSON response containing the messageHello World!.
For more information, see the Express.js documentation.
More of Expressjs
- How do I find Express.js tutorials on YouTube?
- 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?
- How do I use Express.js to parse YAML files?
- How can I disable the X-Powered-By header in Express.js?
- How can I make an XHR request using Express.js?
- How do I implement CSRF protection in an Express.js application?
- How can I use the x-forwarded-for header in Express.js?
- How can I use Express.js to implement websockets in my application?
See more codes...