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 message- Hello World!.
For more information, see the Express.js documentation.
More of Expressjs
- How do I find Express.js tutorials on YouTube?
- How do I use Express.js to parse YAML files?
- How can I disable the X-Powered-By header in Express.js?
- How do Express.js and Spring Boot compare in terms of features and performance?
- How can I set up X-Frame-Options in ExpressJS?
- How do I render a template using Express.js?
- How do I set the time zone in Express.js?
- How can I use the x-forwarded-for header in Express.js?
- How can I use Express.js and Vite together for software development?
- How do I implement CSRF protection in an Express.js application?
See more codes...