找不到模块:无法在 React 中解析“axios”
Module not found: Can’t resolve ‘axios’ in React
要解决错误“找不到模块:错误:无法解析‘axios’”,请确保axios
通过在项目根目录中打开终端并运行命令npm install axios
并重新启动开发服务器来安装软件包。
在项目的根目录(package.json
文件所在的位置)中打开终端并运行以下命令。
# 👇️ with NPM npm install axios # ---------------------------------------------- # 👇️ with YARN yarn add axios
该命令会将axios包添加到项目的依赖项中。
npm start
您现在应该能够axios
在 React.js 应用程序中导入和使用该包。
// ✅ Use correct import 👇️ import axios from 'axios'; import {useState, useEffect} from 'react'; function App() { const [post, setPost] = useState(null); useEffect(() => { axios.get('https://jsonplaceholder.typicode.com/posts/1').then(response => { setPost(response.data); }); }, []); if (!post) return null; console.log(post); return ( <div> <p>{post.title}</p> </div> ); } export default App;
如果错误未解决,请尝试删除您的node_modules
和
package-lock.json
(不是package.json
)文件,重新运行npm install
并重新启动您的 IDE。
# 👇️ delete node_modules and package-lock.json (Windows) rd /s /q "node_modules" del package-lock.json del -f yarn.lock # 👇️ delete node_modules and package-lock.json (macOS/Linux) rm -rf node_modules rm -f package-lock.json rm -f yarn.lock # 👇️ clean npm cache npm cache clean --force npm install
如果您仍然收到“找不到模块:错误:无法解析‘axios’”错误,请打开您的package.json
文件并确保它包含对象中的axios
包dependencies
。
{ // ... rest "dependencies": { "axios": "^0.26.1", }, }
The axios
module should NOT be globally installed or be in your project’s
devDependencies
, it should be in the dependencies
object in your
package.json
file.
You can try to manually add the line and rerun npm install
.
npm install
Or install the latest version of the package:
npm install axios@latest
Conclusion #
To solve the error “Module not found: Error: Can’t resolve ‘axios'”, make sure
to install the axios
package by opening your terminal in your project’s root
directory and running the command npm install axios
and restart your
development server.