【发布时间】: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