Node.js url方法返回null

时间:2014-08-19 16:28:47

标签: javascript node.js

我试图让node.js将http请求属性打印到浏览器。但是,请求网址的属性要么返回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();

当我输入网址localhost:8888

时,我的浏览器输出是

Hello World HTTP响应是200 已收到/已收到。请求url是/,我们的协议是null。此外,我们的主机为null 连接路径是/

我需要获取网址属性。谢谢。

1 个答案:

答案 0 :(得分:3)

这些变量返回未定义的原因是因为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.