Node.js: Read params passed in the URL

2019-06-27 00:48发布

问题:

In rails I do a POST request to my server:

response = Typhoeus::Request.post("http://url.localtunnel.com/request?from=ola&to=ole")
result = JSON.parse(response.body)

In the Node.js app, I want to read From and To:

app.post '/request', (req,res) ->
    console.log "I have received a request, sweet!!"
    sys.log req.params.from
    #sys.log "From: " + req.from + ", To: " + req.to + ", Id: " + req.id

How do I do it?

Thanks

回答1:

The answer is:

Checks query string params (req.query), ex: ?id=12


回答2:

Something like this:

var http = require('http'), url = require('url');
http.createServer(function(request, response) {
    response.writeHead(200, {"Content-Type":"text/plain"});
    var _url = url.parse(request.url, true);
    response.write("Hello " + _url.query["from"] + "!\n"); // etc: _url.query["to"]...
    response.close();
}).listen(8000);

url.parse is a key point... Or you can use querystring.parse(urlString)
You can read more at http://nodejs.org docs section.