Vue+Node.js项目中如何修改Axios的responseURL?
问题
我正尝试使用Axios连接Vue.js前端与Node.js后端,按照教程编写了如下代码:
后端Node.js代码
监听5000端口,提供localhost:5000/signup的POST接口:
app.post("/signup", (req, res) =>{ // receive form data from signup console.log("Hello"); })
监听端口代码:
const PORT = process.env.PORT || 5000; const server = app.listen(PORT, () => { console.log("Server is running on port", server.address().port); });
前端Vue.js代码
submit方法调用Axios请求/api/signup:
methods: { submit() { this.$v.$touch(); axios.post("/api/signup", { fname: this.fname, lname: this.lname, email: this.email, password: this.password, gender: 'Male', dob: this.dob, }).then((res) => { if(res.data.msg === "Email exists"){ console.log("Email exists") } else{ this.$router.push({ path: './browsing' }); } }) // .catch(()=>{ // alert("Something Went Wrong"); // }) }, clear() { this.$v.$reset() this.name = '' this.email = '' this.select = null this.checkbox = false }, }
预期请求会发送到localhost:5000/signup并打印"Hello",但实际responseURL为http://localhost:8081/api/signup,未触发后端逻辑,请问原因是什么?如何将responseURL改为localhost:5000/signup?
原因分析
- 前端请求的
/api/signup是相对路径,会默认拼接当前前端服务的域名和端口(即Vue开发服务器的localhost:8081),导致请求发到前端端口而非后端的5000端口。 - 前端未配置代理转发,也未直接指定完整的后端接口地址,所以请求无法触达到后端服务。
解决方法
方法1:直接使用完整后端接口地址
将Axios请求中的相对路径替换为后端完整URL,把/api/signup改成http://localhost:5000/signup:
axios.post("http://localhost:5000/signup", { fname: this.fname, lname: this.lname, email: this.email, password: this.password, gender: 'Male', dob: this.dob, })
这种方式简单直接,适合开发阶段快速验证,但生产环境需替换为正式后端域名。
方法2:配置Vue代理转发(推荐)
通过代理配置将/api前缀的请求转发到后端,避免代码里写死域名:
- 根据Vue项目类型修改配置文件:
- Vue CLI项目:在根目录创建/修改
vue.config.js:
module.exports = { devServer: { proxy: { '/api': { target: 'http://localhost:5000', changeOrigin: true, pathRewrite: { '^/api': '' } // 移除请求中的/api前缀,转发到后端的/signup } } } }
- Vite项目:在根目录修改
vite.config.js:
export default { server: { proxy: { '/api': { target: 'http://localhost:5000', changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, '') } } } }
- 重启Vue开发服务器后,前端的
/api/signup请求会自动转发到http://localhost:5000/signup,符合预期逻辑。
内容的提问来源于stack exchange,提问作者Nour Hesham
相关产品推荐
相关产品推荐

