Borislav Hadzhiev
Sat Feb 19 2022·2 min read
Photo by Drif Riadh
To solve the "Cannot find module axios
or its corresponding type
declarations" error, install the module by running the command
npm install axios
. You can then import axios
with the following line of code
import axios from 'axios'
.
Make sure to install the axios
module, by opening your terminal in your
project's root directory and running the following command:
npm install axios
The axios
module includes TypeScript definitions, so you don't have to install
the types separately.
Now you should be able to import the axios module with the following line of code.
import axios from 'axios'; console.log(axios);
axios
module.If the error is not resolved, try to delete your node_modules
and
package-lock.json
files, re-run npm install
and restart your IDE.
rm -rf node_modules package-lock.json npm install
Make sure to restart your IDE if the error still persists. VSCode glitches often and a reboot solves things sometimes.
If you want to read more about making HTTP requests with axios
in TypeScript,
check out my other article -
Making Http requests with Axios in TypeScript.
Here is an example of making an HTTP GET
request with axios
using
TypeScript.
import axios from 'axios'; type User = { id: number; email: string; first_name: string; }; type GetUsersResponse = { data: User[]; }; async function getUsers() { try { // 👇️ const data: GetUsersResponse const { data, status } = await axios.get<GetUsersResponse>( 'https://reqres.in/api/users', { headers: { Accept: 'application/json', }, }, ); console.log(JSON.stringify(data, null, 4)); // 👇️ "response status is: 200" console.log('response status is: ', status); return data; } catch (error) { if (axios.isAxiosError(error)) { console.log('error message: ', error.message); return error.message; } else { console.log('unexpected error: ', error); return 'An unexpected error occurred'; } } } getUsers();
You can read more about how to use axios
with TypeScript by checking out my
other article -
Making Http requests with Axios in TypeScript.