如何在节点中使用全局URLSearchParams

Mar*_*olt 15 javascript node.js

我正在编写一个(客户端)JavaScript库(节点/角度模块).在这个库中,我使用了URLSearchParams类.

const form = new URLSearchParams();
form.set('username', data.username);
form.set('password', data.pass);
Run Code Online (Sandbox Code Playgroud)

由于这是一个共享库,因此它被打包为npm模块.但是,在运行mocha单元测试时,我收到了未定义URLSearchParams的错误.原因似乎是节点在全局范围内没有URLSearchParams,但必须使用require('url')以下方法导入:

$ node
> new URLSearchParams()
ReferenceError: URLSearchParams is not defined
    at repl:1:5
    at sigintHandlersWrap (vm.js:22:35)
    at sigintHandlersWrap (vm.js:73:12)
    at ContextifyScript.Script.runInThisContext (vm.js:21:12)
    at REPLServer.defaultEval (repl.js:340:29)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.<anonymous> (repl.js:538:10)
    at emitOne (events.js:101:20)
    at REPLServer.emit (events.js:188:7)
Run Code Online (Sandbox Code Playgroud)

如何使URLSearchParams可用于节点内的客户端代码,以便我可以使用mocha测试库?

这不起作用:

> global.URLSearchParams = require('url').URLSearchParams
undefined
> new URLSearchParams()
TypeError: URLSearchParams is not a constructor
    at repl:1:1
    at sigintHandlersWrap (vm.js:22:35)
    at sigintHandlersWrap (vm.js:73:12)
    at ContextifyScript.Script.runInThisContext (vm.js:21:12)
    at REPLServer.defaultEval (repl.js:340:29)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.<anonymous> (repl.js:538:10)
    at emitOne (events.js:101:20)
    at REPLServer.emit (events.js:188:7)
Run Code Online (Sandbox Code Playgroud)

mar*_*usw 22

更新:节点v10具有URLSearchParams全局对象的内置可用性,因此可以按问题中的预期直接使用它.

较旧版本的Node:

一种选择是在测试运行器的启动脚本中将其设置为全局:

import { URLSearchParams } from 'url';
global.URLSearchParams = URLSearchParams
Run Code Online (Sandbox Code Playgroud)

例如,使用Jest,您可以使用setupTestFrameworkScriptFile指向上面的启动脚本.

作为旁注,如果您想在创建服务器端Webpack通用代码包时获得类似的结果,您可以使用Webpack实现此目的ProvidePlugin:

{
  name: 'server',
  target: 'node',
  // ...
  plugins: [
    // ...
    new webpack.ProvidePlugin({
      URLSearchParams: ['url', 'URLSearchParams'],
      fetch: 'node-fetch',
    }),
  ],
}
Run Code Online (Sandbox Code Playgroud)

  • Node v10在`global`对象上内置了`URLSearchParams`,因此可以在没有上述设置的情况下使用它. (4认同)

Bru*_*sky 9

在使用 Node8.10 的 AWS Lambda 中,我必须执行以下操作:

const {URLSearchParams} = require('url')
const sp = new URLSearchParams(request.querystring)
Run Code Online (Sandbox Code Playgroud)

或者

const url = require('url')
const sp = new url.URLSearchParams(request.querystring)
Run Code Online (Sandbox Code Playgroud)