0

In the following code I'm creating an API and I want to pass a pathname and check it using switch statements to pass GET, POST, etc.

But it seems I am doing something wrong because it doesn't seem to pass the pathname but the localhost:8080..

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

var server = http.createServer(function (req, res) {
    var parsedURL = URL.parse(req.URL, true);

    switch (parsedURL) {
        case '/api/something':
        if (parsedURL.query.id) {
            findProductById(id, req, res);
        }
        else {
            findAll(req, res);
        }
        break;
        default;
        res.end('End of connection');
    }
});
server.listen(8080);
console.log("Running");  

What am I doing wrong? Am I using the URL properly? Or missing something with the parsing?

Thanks for help!

3
  • Shouldn't that be switch(parsedURL.pathname) { if you want the pathname? Commented Jan 12, 2016 at 22:09
  • What is the value you are getting for req.URL? Commented Jan 12, 2016 at 22:15
  • @JoachimIsaksson - yes it should :) thanks! Commented Jan 12, 2016 at 23:19

1 Answer 1

1

Your require should look like this:

var URL = require('url');

Node couldn't find the right module, it's all lowercase.

Also, the default statement in your switch case is using improper syntax. Try:

default: res.end('End of connection');
Sign up to request clarification or add additional context in comments.

1 Comment

this definitely helped, as nodemon has been showing me that cannot find url module and I did not know what was that and obviously that stupid syntax, but it still seems not working...

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.