expressjsHow do I set and use headers in Express.js?
To set and use headers in Express.js, you can use the app.use()
and res.header()
methods.
The app.use()
method is used to set the headers for all requests and responses. For example, the following code sets the Content-Type
header to application/json
for all requests and responses:
app.use(function (req, res, next) {
res.header("Content-Type", "application/json");
next();
});
The res.header()
method is used to set the headers for a specific request and response. For example, the following code sets the Content-Type
header to application/json
for a specific response:
app.get("/", function (req, res) {
res.header("Content-Type", "application/json");
res.send({"message": "Hello World!"});
});
Output example
{"message": "Hello World!"}
The req.header()
method is used to get the headers for a specific request. For example, the following code gets the Content-Type
header for a specific request:
app.get("/", function (req, res) {
let contentType = req.header("Content-Type");
console.log(contentType);
});
Output example
application/json
Helpful links
More of Expressjs
- How can I use Node.js and Express together to create a web application?
- How do I find Express.js tutorials on YouTube?
- How do I use Express.js to handle x-www-form-urlencoded data?
- How can I use Express.js to prevent XSS attacks?
- How do I use the expressjs urlencoded middleware?
- How do I use Zod with Express.js?
- How do I use Yarn to add Express.js to my project?
- 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 disable the X-Powered-By header in Express.js?
See more codes...