【问题标题】:The signature of 'parse' is deprecated'parse' 的签名已被弃用
【发布时间】:2021-12-05 23:05:58
【问题描述】:

我正在创建一个节点服务器,但有一个过时的功能。我的代码中有以下错误:

The signature '(urlString: string): UrlWithStringQuery' of 'parse' is deprecated.ts(6387)
url.d.ts(63, 8): The declaration was marked as deprecated here.
(alias) parse(urlString: string): UrlWithStringQuery (+3 overloads)
import parse
The url.parse() method takes a URL string, parses it, and returns a URL object.

A TypeError is thrown if urlString is not a string.

我的代码是:

    server.on('request', function (req, res) {
 var filename = parse(req.url).pathname,
     fullPath,
     extension;

 ...

我可以用什么来代替 parse(req.url).pathname?

【问题讨论】:

  • 如果您的代码是纯 JS,为什么会出现 TS 错误?您能否添加更多详细信息来准确解释您在这里所做的事情,最好是某种minimal reproducible example 描述?
  • 很确定它希望您在较新的版本中使用new URL(...)nodejs.org/api/…你使用的是什么版本的节点?是否与 TypeScript 节点版本类型匹配?

标签: javascript node.js parsing server deprecated


【解决方案1】:

我最近遇到了这个问题。正如您的错误所暗示的那样,Node.js API (v14.18.1) 文档中的 url.parse 显示为已弃用/旧版。引用的 WHATWG Standard URL API 替换了 url.parse,可以在 new URL 条目下找到以创建 URL。

以下是 API 文档中提供的代码示例:

const url = require('url');
// `new URL(input[, base])` where `base` is required if `input` is a relative path
const myURL = new URL('/foo', 'https://example.org/');

以您的代码为例:

const url = require('url'); // including the url library
const base = 'https://base-hostname/'; // sample base hostname to use in the URL constructor
...
server.on('request', function (req, res) {
  var filename = new url.URL(req.url, base).pathname,
    fullPath,
    extension;

【讨论】:

    猜你喜欢
    • 2016-06-08
    • 2019-04-04
    • 2018-12-12
    • 2014-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多