Reputation: 123
How do you get the get request string into a viable, like if someone goes to www.mypage.com/yo , how can I get node to return "yo" into a variable?
var http = require('http');
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
var stringrequested = ??????
response.end(stringrequested);
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
// Put a friendly message on the terminal
console.log("Server running");
Upvotes: 2
Views: 2643
Reputation: 13405
request.url
contains the requested uri:
var stringrqeuested = request.url; // /yo
If you want just the "yo", you can remove the leading slash like this:
var stringrqeuested = request.url.substr(1); // yo
But request.url
contains also the query string e.g. /yo?a=b&c=d
. If you don't want that, you'll need to parse the url:
var stringrequested = require('url').parse(request.url).pathname; // /yo
var stringrequested = require('url').parse(request.url).pathname.substr(1); // yo
Here is an example from the documentation.
node> require('url').parse('/status?name=ryan', true)
{ href: '/status?name=ryan',
search: '?name=ryan',
query: { name: 'ryan' },
pathname: '/status' }
Upvotes: 2
Reputation: 4423
Cut off the first character of the URL (/
):
request.url.substr(1)
Upvotes: 0