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 set up a YAML configuration file for a Node.js Express application?
- How do I find Express.js tutorials on YouTube?
- How do Express.js and Node.js differ in terms of usage?
- How can I create and use models in Express.js?
- How can I use Express.js to develop a web application?
- How can I use the x-forwarded-for header in Express.js?
- How can I use Express.js to prevent XSS attacks?
- How can I use Express.js with TypeScript?
- How do I manage user roles in Express.js?
- How can I use Express.js and SQLite together to develop a web application?
See more codes...