how to append response header in node
To append a response header in Node.js, you can use the setHeader
method of the response object. Here are the steps to do it:
Access the response object: In your Node.js application, you will have a callback function that handles the HTTP request and response. Inside this function, you can access the response object.
Use the
setHeader
method: Call thesetHeader
method on the response object to set the desired header. The method takes two arguments: the header name and the header value.Example code: Here's an example that demonstrates how to append a response header in Node.js:
const http = require('http');
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/plain');
res.setHeader('X-Custom-Header', 'Custom Value');
res.end('Hello, world!');
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example, we set the Content-Type
header to text/plain
and the X-Custom-Header
to Custom Value
. You can modify these values according to your requirements.
That's it! The response header will be appended to the HTTP response and sent back to the client.