1

I am using the MEAN JS framework to create an app. My purpose is to detect a query parameter at the time of website load, and then set certain parameters for the app.

My server.js :

exports = module.exports = app;

Server controller

exports.index = function(req, res) {

 console.log('URL is ' + req.url);
 console.log('Path is ' + req.path);
 var param1 = req.query.param1;
 console.log('Parameter : ' + param1);
 console.dir(req.query);

 res.render('index', {
    request: req,
    myparam : param1 //Setting my custom parameter
 });
};

URL accessed :

http://localhost:3000/#!/?param1=test

Output :

URL is /
Path is /
Parameter : undefined
{}

The query parameter is not being detected at all. Can someone please explain why this could be happening. I know Express ignores parameters while routing, but does it strip the url as well?

EDIT :

It was the angular fragment url which was causing the error. Once I made the URLs normal, Express detected all query parameters using the above method.

EDIT 2 :

Detailed answer here

MEANJS Get URL Parameters

Community
  • 1
  • 1
kvnam
  • 1,285
  • 2
  • 19
  • 34
  • you could use body-parser and get the param using: req.body.param1 – Duly Kinsky Jul 26 '16 at 05:39
  • Thanks, will give it a try. Though query string parameters should be stored in req.query right? How is it not even detecting any? – kvnam Jul 26 '16 at 05:49
  • Try req.QueryString("param1") – Duly Kinsky Jul 26 '16 at 05:53
  • req.body is empty as well. For req.QueryString, it is giving an error stating no such function exists. – kvnam Jul 26 '16 at 05:55
  • what is the exclamation point for? first time I have seen that in the url – Duly Kinsky Jul 26 '16 at 05:59
  • That's just the Angular Url, the # is appended by default. The ! is being added by my MEANJS framework. Haven't made the URL pretty yet. – kvnam Jul 26 '16 at 06:05
  • I found this post: http://stackoverflow.com/questions/6912584/how-to-get-get-query-string-variables-in-express-js-on-node-js; hope it helps! – Duly Kinsky Jul 26 '16 at 06:26
  • No luck, going to go check if the url fragment #! could be causing this problem. Thanks for the suggestions :) – kvnam Jul 26 '16 at 06:34
  • Possible duplicate of [MEANJS Get URL Parameters](http://stackoverflow.com/questions/27404935/meanjs-get-url-parameters) – kvnam Jul 26 '16 at 18:22

1 Answers1

0

Since I don't have access to the full code, I'm not 100% sure this is the correct solution for you.

Although it works fine for me:

Define:

var query = require('url').parse(req.url,true).query;

And then:

var param1 = query.param1

Let me know if this helps :)

felipenbrito
  • 70
  • 1
  • 9
  • 1
    The error was caused due to the #! added to the URL by Angular and the MEANJS framework. Express was not detecting any query string parameters beyond the #!. I switched to clean URLs and that solved the problem. Thanks for suggestion though :). – kvnam Jul 26 '16 at 18:22