Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use URLSearchParams in a Node.js and TypeScript project [duplicate]

I have a Node.js project that is built with TypeScript I'm trying to use URLSearchParams, however I can see the following error:

Cannot find name 'URLSearchParams'.ts(2304)
const params = new URLSearchParams();
params.append("foo", 5);

typescript: ^3.9.7
node.js: v12.16.3
like image 993
Kay Avatar asked Aug 04 '20 12:08

Kay


People also ask

Can I use URLSearchParams in node?

Node is an open source project that is used to create dynamic web applications. The URLSearchParams API is an interface. It defines different utility that is required to work with the query string of the URL.


1 Answers

While URLSearchParams has lived on the global object in node since v10.0.0, it can be hard to pull ambient type information from there.

The URLSearchParams class lives in the url module, so you can also import it directly from there:

import { URLSearchParams } from "url"

then use it like this:

let queryString = new URLSearchParams({page: "1", pagesize: "100"}).toString();

Also, make sure you install types for node

npm install @types/node --save-dev

Further Reading

  • How to use global URLSearchParams in node
like image 109
KyleMit Avatar answered Oct 17 '22 23:10

KyleMit