0

How can you use URL query strings in NodeJS like PHP's $_GET["query"] command?

http://php.net/manual/en/reserved.variables.get.php

Say for example you wanted to extend the code below to use a ?option=1 on the /page001 part.

So visiting ServerURL/page001?option=1 would write "Page1: Option 001 Selected".

And ServerURL/page001?option=2 would write "Page1: Option 002 Selected" etc.

var http = require('http');
var fs = require("fs");
var location = require('location-href');

var HttpDispatcher = require('httpdispatcher');
var dispatcher = new HttpDispatcher();

////////////////////

var http=require('http');
var url=require('url');

var server=http.createServer(function(req,res){
    var pathname=url.parse(req.url).pathname;
    switch(pathname){
        case '/page001':
            res.end('<div id="page001"><h2>Page 001</h2><div>Page 001 Content</div></div>');
            console.log("Page 001 Loaded");
        break;
        case '/page002':
            res.end('<div id="page002"><h2>Page 002</h2><div>Page 002 Content</div></div>');
            console.log("Page 002 Loaded");
        break;
        default:
            res.end('<div id="default"><h2>Default</h2><div>This is the default page</div></div>');
            console.log("Default page was loaded");
        break;
    }

}).listen(8080);

console.log("Running on Port 8080");
1
  • You could try inspecting the request object req (by console.log, for example) and see what's inside, there's a lot of interesting stuff in it. Commented Mar 30, 2017 at 12:18

1 Answer 1

2

You'll have to parse the .search property of the URL that you parsed. There's plenty of examples on how to parse a query string on this site.

var reqUrl = url.parse(req.url),
    search = reqUrl.search,
    pathname = reqUrl.pathname;
Sign up to request clarification or add additional context in comments.

1 Comment

Works great thanks, i will accept this answer when possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.