已安装axios但导入报错,请求解决前后端数据交互问题
Axios模块导入报错的解决方案
问题场景
已执行npm install axios安装Axios,在前端JS代码中使用import axios from 'axios'导入,尝试实现POST/GET请求时,出现以下报错:
Uncaught TypeError: Error resolving module specifier “axios”. Relative module specifiers must start with “./”, “../” or “/”
相关代码
package.json
{ "name": "ceniplex-tickets", "version": "1.0.0", "description": "ticket booking app", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Aswin Anilkumar", "license": "ISC", "devDependencies": { "parcel": "^2.8.1", "parcel-bundler": "^1.8.1" }, "dependencies": { "axios": "^1.2.1" } }
前端JS代码
import axios from 'axios'; class Model { constructor() { this.array = [] } getArray() { return this.array; } async loadTicketsFromBackend() { const req = await axios.get('http://localhost:3000/booking') const booking = req.data; console.log(booking); } async setArray(data) { const res = await axios.post('http://localhost:3000/booking',data) return res; } } export default Model;
解决方法
这个报错的核心原因是:浏览器原生ES模块只支持相对路径(.//../)或绝对路径的模块导入,不识别npm包名;而你虽然安装了Parcel打包工具,但没有通过它来构建/启动项目,导致浏览器直接加载未处理的原生ES模块。
正确解决步骤
添加Parcel启动脚本
在package.json的scripts字段中添加启动命令(假设你的项目入口HTML文件是index.html,请替换为实际文件名):"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "parcel index.html" }通过Parcel启动项目
在终端执行以下命令:npm run startParcel会自动解析所有npm依赖,将Axios打包到最终的输出文件中,此时
import axios from 'axios'就能正常工作。
临时测试方案(不推荐用于生产环境)
如果不想使用打包工具,可通过CDN方式引入Axios:在项目的HTML文件中添加Axios的CDN脚本标签(可从Axios官方获取对应版本的CDN地址),之后在JS代码中无需import,直接使用全局的axios对象即可。
内容的提问来源于stack exchange,提问作者Abhinand K
相关产品推荐
相关产品推荐

