Node.js is a very popular server-side JavaScript development environment. Like other web application frameworks, Node.js can also control the data format and information received by the client by setting response headers.
The response header is part of the HTTP response and contains some metadata that describes the content of the response message. For example, the response header contains Content-Type, which is used to specify the content type returned by the server and can be set to text/plain, application/json, etc. Also included is Cache-Control, which specifies how the browser caches the response.
In Node.js, we can use the response object to set the response header. The response object is an object of the HTTP server that contains information about the current response. The following is an example of how to use response to set the response header:
const http = require('http'); http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.write('<h1>Hello World</h1>'); res.end(); }).listen(3000);
In the above example, we use the setHeader method to set the Content-Type header, which specifies the content type of the response as text/html. We also use the write method to send a header to the client, and then use the end method to end the response.
In addition to the setHeader method, Node.js also provides more methods for setting response headers, such as:
In addition to using these methods to set response headers, we can also use third-party modules to set response headers more conveniently. For example, express.js is a popular framework for Node.js that provides a simpler and more advanced API for setting response headers. Here is an example of how to set response headers in express.js:
const express = require('express'); const app = express(); app.get('/', (req, res) => { res.set('Content-Type', 'text/html'); res.send('<h1>Hello World</h1>'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });
In the above example, we have set the Content-Type header using the set method and then sent the response to the client using the send method.
In short, controlling the response header is very important because it can help us control the data format and information received by the client. In Node.js, we can use the response object or third-party modules to set response headers, which makes our code simpler and easier to maintain.
The above is the detailed content of nodejs sets the corresponding header. For more information, please follow other related articles on the PHP Chinese website!