During the development of my react app with postgres, express, node, and typescript, I ran into an issue while working on the backend code. The problem arises when trying to utilize URLSearchParams.
index.js
import express from 'express';
import cors from 'cors';
import * as recipeAPI from './recipe-api'
const app = express();
app.use(express.json());
app.use(cors());
app.get("/api/recipe/search", async (req,res) => {
const searchTerm = req.query.searchTerm as string;
const page = parseInt(req.query.page as string);
const results = await recipeAPI.searchRecipes(searchTerm, page);
return res.json(results);
})
app.listen(5000, () => {
console.log("Server running on localhost 5000")
})
recipe-api-ts
import { error } from "console";
import { URLSearchParams } from "url";
const API_KEY = process.env.API_KEY;
export const searchRecipes = async (searchTerm: string, page: number) => {
if(!API_KEY){
throw new Error("API key not found")
}
const baseURL = "https://api.spoonacular.com/recipes/complexSearch";
const url = new URL(baseURL);
const queryParams = {
apiKey: API_KEY,
query: searchTerm,
number: 10,
offset: (page - 1) * 10,
};
const searchTerms = new URLSearchParams(queryParams);
url.search = searchTerms.toString();
try {
const searchResponse = await fetch(url.toString());
const resultsJson = await searchResponse.json();
return resultsJson;
} catch (error) {
console.error(error);
}
};
An error occurs in the recipe-api-ts file at this line
const searchTerms = new URLSearchParams(queryParams);
TSError: ⨯ Unable to compile TypeScript:
src/recipe-api.ts:23:43 - error TS2345: Argument of type '{ apiKey: string; query: string; number: number; offset: number; }' is not assignable to parameter of type 'string | URLSearchParams | Record
23 const searchTerms = new URLSearchParams(queryParams);
This error appears after compilation.