【问题标题】:Node.js url methods return nullNode.js url 方法返回 null
【发布时间】:2014-08-19 16:28:46
【问题描述】:

我正在尝试让 node.js 将 http 请求属性打印到浏览器。但是,请求 url 的属性要么返回 null,要么根本不打印。这是服务器的代码(server.js):

var http = require('http');
var url = require('url');
function start() {
 function onRequest(request, response) {
    var pathname = url.parse(request.url, true).pathname;
    var protocol = url.parse(request.url, true).protocol;
    var hostname = url.parse(request.url, true).host;
    var path = url.parse(request.url, true).path;
    response.writeHead(200, {"Content-Type": "text/plain"}); 
    response.write("Hello World"); //this is the text that is sent back
    response.write("\nThe HTTP response is " + response.statusCode);
    response.write("\nRequest for "+ pathname +" has been received. The request url is " + request.url + " and our protocol is " + protocol +".Also, our host is " + hostname);
    response.write("\nThe concatenated path is " + path);
    response.end(); //this is the end of the response
 }
 var new_server = http.createServer(onRequest).listen(8888);
} //end of start function
exports.start = start; 

执行这个的索引文件是index.js

var server = require("./server");
console.log("To see what the sever responds with, go to localhost:8888.");
server.start();

我的浏览器输出是,当我在 url 栏输入 localhost:8888 时

你好世界 HTTP 响应为 200 已收到 / 的请求。请求 url 是 / 并且我们的协议是 null。另外,我们的主机是 null 连接路径是/

我需要获取 url 属性。谢谢。

【问题讨论】:

  • 你真的检查过request.url的内容吗?
  • request.url 不包括整个 URL,它只是路径和查询(例如 /page?a=1&b=2)。它取自 HTTP 请求的第一行,其中不包括域/协议/任何内容。

标签: javascript node.js


【解决方案1】:

这些变量返回 undefined 的原因是 url 只包含路径。协议和主机存储在别处。以 node.js 文档中的这个例子为例:

var url = require('url');
console.log( url.parse(
    'http://user:pass@host.com:8080/p/a/t/h?query=string#hash', true
  ));

这将返回以下对象:

{
  href: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash',
  protocol: 'http:',
  host: 'user:pass@host.com:8080',
  auth: 'user:pass',
  hostname: 'host.com',
  port: '8080',
  pathname: '/p/a/t/h',
  search: '?query=string',
  query: { query: 'string' },
  hash: '#hash',
  slashes: true
} 

这些值存在于 URL 中,因此它们存在于对象中。 localhost:8888 URL 没有这些。

另一方面,请求对象有三个重要方面:urlmethodheaders。如果您尝试这样做,我怀疑您会找到您正在寻找的信息:

var urlStr = 'http://' + req.headers.host + req.url,
    parsedURL = url.parse( urlStr ,true );

console.log(parsedURL);
//this should give you the data you are looking for.

【讨论】:

    猜你喜欢
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    相关资源
    最近更新 更多