如何使用新的 URL API 获取请求详细信息?

时间:2021-06-29 11:14:14

标签: node.js url node-modules

在学习了 Node.js 教程后,我尝试获取请求的详细信息,如下所示:

const url = require('url');

http
    .createServer((req, res) => {
        *let parsedUrl = url.parse(req.url, true);*
        
        res.write('---------->  ');
        res.write(parsedUrl.search);
        res.write(parsedUrl.search);
        re.write(parsedUrl.pathname);
        res.write('  <----------');
        res.end();
    })
    .listen(3000, () => cl('Listening on port 3000.'));

这工作正常,但我收到一条警告,提示 url.parse() 已被弃用,而我应该使用 new URL() API。但问题是,使用 url.parse() 我可以将 req.url 作为参数传递,而使用 new URL() 我必须传递一个字符串作为参数,因此我不能使用 req.url获取请求详细信息。还是我遗漏了什么?

http
    .createServer((req, res) => {
        *let myUrl = new URL(req.url.toString());*
        
        res.write(myUrl);
        res.end();
    })
    .listen(3000, () => cl('Listening on port 3000.'));

如果 curl 这个 URL curl http://localhost:3000/test?hello=world,我会收到这个错误 TypeError [ERR_INVALID_URL]: Invalid URL: /test?hello=world

0 个答案:

没有答案