gpt4 book ai didi

javascript - Node.js url 方法返回 null

转载 作者:搜寻专家 更新时间:2023-11-01 00:43:52 24 4
gpt4 key购买 nike

我正在尝试让 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 时,我的浏览器输出是

Hello World HTTP 响应为 200已收到/的请求。请求 url 是/并且我们的协议(protocol)是空的。另外,我们的主机是空的连接的路径是/

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

最佳答案

这些变量返回未定义的原因是因为 url 只包含路径。协议(protocol)和主机存储在别处。从 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.

关于javascript - Node.js url 方法返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25388504/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com