我一直在尝试使用这里描述的节点js的url模块:https://nodejs.org/api/url.html#url_url,但我似乎无法得到简单的例子工作。我希望能够建立一个网址,但使用下面的代码,URL不是函数node.js
const URL = require('url');
const apiUrl = new URL('myapi.com/');
apiUrl.searchParams.set('tickers', tickers);
console.log(apiUrl.href);
我遇到了错误,该URL不是一个函数。我与该网站建议初始化URL过其他方式尝试这个,因为
const { URL } = require('url');
但是,这导致第一开括号语法错误。 如何使用url模块实际操作url?
编辑:
在MinusFour的建议的光,现在我了这里:
const URL = require('url').Url;
const apiUrl = new URL('myapi.com/');
console.log(apiUrl);
apiUrl.search = 'tickers=[\'msft\']';
console.log(apiUrl.href);
这并编译并没有出现任何的差错运行,但日志
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: null,
query: null,
pathname: null,
path: null,
href: null }
null
这并不是我所希望的。
“但是这会导致第一个开放括号上出现语法错误。”这是因为你使用的是旧版本的node.js。请参阅https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment – undefined