nodeJS - where exactly can I put the Content Security Policy

后端 未结 3 776
梦谈多话
梦谈多话 2021-01-04 04:27

I don\'t know where to apply the Content Security Policy (CSP) snippet below in my code;

Content-Security-Policy: script-src \'self\' https://apis.google.com         


        
3条回答
  •  情歌与酒
    2021-01-04 05:20

    For a node.js application without using any external framework e.g. 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("

    Hello, Security Headers!

    "); }); }).listen(8080);

    See the node.js documentation for more details on setting headers on the response object

提交回复
热议问题