【问题标题】:Javascript: Reading node.js HTTP messageJavascript:读取 node.js HTTP 消息
【发布时间】:2014-04-14 18:46:50
【问题描述】:

我有一个包含以下信息的 HTTP 数据包:

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

使用node.js,如何提取名称字段?我尝试查看邮件正文并发现它为空,我不确定我还有哪些其他选项或如何获取此值。提前致谢

【问题讨论】:

  • 可以分享一下你目前掌握的相关代码吗?您是否使用任何特定的 HTTP 服务器库或框架?有些人会创建一个request.query 对象,该对象将name 作为属性。但是,如果您只是使用 Node 自己的 API,则必须自己 parse request.url

标签: javascript node.js http http-get


【解决方案1】:

您并不总是需要将 Express 用于简单的 http 服务器解决方案,您也可以为此使用内置模块:

请求结果: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);

【讨论】:

    猜你喜欢
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2018-06-25
    • 2018-03-21
    • 2011-02-17
    • 2015-05-12
    • 2011-01-12
    相关资源
    最近更新 更多