X

Node.js

Parsing Request

/*

Searching the request url for a query string

*/

The request object is the http.IncomingMessage. This is the object that the client sends to the server every time a request is made. We can access the info of the request by using the request object.

Declare requestQuery and requestString variables, then start up the http server. We're going to use regular expressions to search the request url for a ?. If there is no ? then there is no request data, if there is a ? then we'll bring back the query string.

The str.search(query) method searches a string for a query. If it finds the query in the search it returns the first index of the match. If it doesn't find a match it returns -1. If we find a match we're going to use str.substring(start, end) to return the matching characters. The arguments are the start index and the end index.

/*

Parsing the request

*/

We're going to put the request method, url and query into our requestString variable. Then, we'll use a for in loop to put each of the request headers into our requestString, make a console.log of our requestString and end the response.

About the Author

Christopher Howard

Chris is a Javascript developer with a minor in UI design. He values programming in vanilla code. Fill out the form below to contact him.