Question

I have an HTTP packet with the following information:

GET /something?name=joe HTTP/1.1
Host: hostname:8080
Connection: keep-alive
...

Using node.js, how do I extract the name field? I have tried looking through the message body and have found it is null, and I am unsure what other options I have or how to get this value. Thanks in advance

Était-ce utile?

La solution

Well not always you need to use Express for simple http server solution, you could also the built in modules for this:

The result of requesting: http://example:8080/user?name=Mike&age=32

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

http.createServer(function(req, res) {
    var path = '',
        parsed = url.parse(req.url, true);

    if (parsed.pathname === '/user') {

        // Requested:  { protocol: null,
        //   slashes: null,
        //   auth: null,
        //   host: null,
        //   port: null,
        //   hostname: null,
        //   hash: null,
        //   search: '?name=Mike&age=32',
        //   query: { name: 'Mike', age: '32' },
        //   pathname: '/user',
        //   path: '/user?name=Mike&age=32',
        //   href: '/user?name=Mike&age=32' }
        console.log('Requested: ', parsed);
        path = parsed.pathname;
    }

    res.end('Found path ' + path);
}).listen(8080);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top