简体   繁体   中英

CORS Origin header

I'm trying to check if the Origin header is set in the client's request. At the moment the first if statement is what i'm trying to do but it doesn't work. How can this be fixed?

 const http = require('http');
 const port = 3000;

 http.createServer((req, res) => {
    headers = {
       'Access-Control-Allow-Origin': '*',
       'Access-Control-Allow-Methods': 'GET, POST, HEAD',
       'Access-Control-Max-Age': '7200'       

   };

   if (req.headers['ORIGIN'] === null) {
       res.statusCode = 400;
       res.end("Origin header not in the request")
   }

   if (req.method === 'HEAD') {
       res.writeHead(200, headers);
    res.end();
   }
   if (req.method === 'GET') {
       res.writeHead(200, headers);
       res.end("I was requested using CORS!");
   }

   if (req.method === 'POST') {
       res.writeHead(200, req.headers);
       res.end("I was requested using CORS!");
   }
   if (req.method =! 'GET' && req.method != 'POST' && req.method != 'HEAD'){
       res.writeHead(405, headers);
       res.end("Request used a HTTP method which is not allowed.");
   }
}).listen(port);

Headers that don't exist will be undefined , not null .

That isn't a very useful check though. It just stops people visiting the URL directly in a browser, or from making a same origin request with JS. It won't prevent them from using other tools to make HTTP requests.

HTTP headers are case insensitive. From RFC 2616 Section 4.2 :

Each header field consists of a name followed by a colon (":") and the field value. Field names are case-insensitive.

For this reason, NodeJS's HTTP module will convert all header names to lowercase. That being said, you can access the raw header names via req.rawHeaders .

To make your code work, I would check for a lowercase origin header, and I would also check if its value is undefined rather than null because if a header does not exist in a request its value will be undefined .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM