How to parse the first line of the http header?

Is there any javascript function to parse the first line of the http header?

GET /page/?id=173&sessid=mk9sa774 HTTP/1.1 

URL encoded.

I would like to get an object, for example:

 { "method" : "GET", "url" : "/page/", "parameters": { "id" : 173, "sessid" : "mk9sa774" } } 

I searched a lot, but I did not find anything useful.

thanks in advance,

+4
source share
1 answer

First you can break into spaces:

 var lineParts = line.split(' '); 

Now you can get the method, unshared path and version:

 var method = lineParts[0]; var path = lineParts[1]; var version = lineParts[2]; 

Then you can split the path into a query string and parts of a string without a query:

 var queryStringIndex = path.indexOf('?'); var url, queryString; if(queryStringIndex == -1) { url = path, queryString = ''; }else{ url = path.substring(0, queryStringIndex); // I believe that technically the query string includes the '?', // but that not important for us. queryString = path.substring(queryStringIndex + 1); } 

If there is a query string, we can break it into key=value strings:

 var queryStringParts = []; if(queryStringIndex != -1) { queryStringParts = queryString.split('&'); } 

Then we can undo them and fill them with an object:

 var parameters = {}; queryStringParts.forEach(function(part) { var equalsIndex = part.indexOf('='); var key, value; if(equalsIndex == -1) { key = part, value = ""; }else{ key = part.substring(0, equalsIndex); value = part.substring(equalsIndex + 1); } key = decodeURIComponent(key); value = decodeURIComponent(value); parameters[key] = value; }); 

If you really want to, you can put all this data in an object:

 return { method: method, url: url, version: version, parameters: parameters }; 

If you are in a browser environment, this is the only way to do this. If you use Node.JS, it can handle URL parsing .

+6
source

Source: https://habr.com/ru/post/1403353/


All Articles