对于不使用任何外部框架的node.js
应用程序,例如:express
const http = require('http');
http.createServer((request, response) => {
request.on('error', (err) => {
console.error(err);
// for this simple example I am not including the data event
// e.g. if the request contains data in the body
}).on('end', () => {
response.on('error', (err) => {
console.error(err);
});
// you can set your headers with setHeader or
// use writeHead as a "shortcut" to include the statusCode.
// Note writeHead won't cache results internally
// and if used in conjuction with setHeader will take some sort of "precedence"
response.writeHead(200, {
"Content-Security-Policy": "default-src 'self'"
// other security headers here...
});
response.end("<html><body><h1>Hello, Security Headers!</h1></body></html>");
});
}).listen(8080);
有关在响应对象上设置标头的更多详细信息,请参阅 node.js 文档