Proxy error: Could not proxy request /api2/users/login from localhost:8080 to localhost:3000 (ENOTFO

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/Reagan_/article/details/97498160

昨天遇到了这个问题(如标题),查了很多资料都没有解决,最后终于解决了,记录一下。

问题描述:因为node服务运行在localhost:3000端口,vue运行在localhost:8080端口,不同端口存在跨域问题。
所以我使用了反向代理处理。
在vue.config.js里:

proxy:{
    '/api2':{
        target:'http://localhost:3000', 
        changeOrigin:true, 
    }
}

我这里是vue-cli3,所以是vue.config.js,如果是vue-cli2,就在config文件夹里的index.js里面。

在发送axios后,

toLogin(){
    this.axios.post('/api2/users/login',{
        username:this.username,
        password:this.password
    }).then((res)=>{
        console.log(res);
    }).catch((res) => {
        alert("错误:" + res);
    });
}

出现了这样的问题。
在这里插入图片描述

在network里面看

Proxy error: Could not proxy request /api2/users/login from localhost:8080 to localhost:3000 (ENOTFOUND).

解决:
1.在前端部分的项目目录里面,找到配置文件package.json
本来是这样:

"scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build"
},

给它加上start和server:

"scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "start": "node index.js",
    "server": "nodemon index.js --ignore client"
},

问题解决了。
在这里插入图片描述

导致这个问题也有可能是路径的问题

  • proxy代理部分:
proxy:{
    '/api2':{   //1
        target:'http://localhost:3000',   //2
        changeOrigin:true, 
    }
}

1.这里路径要注意
2.这里在mac和windows上写法不一样
windows:

扫描二维码关注公众号,回复: 7590995 查看本文章
"target": "localhost:3000"

mac:

"target": "http://127.0.0.1:3000"
  • 发送axios部分:
this.axios.post('/api2/users/login'

/api2这个地方也要注意拼接得对不对

猜你喜欢

转载自blog.csdn.net/Reagan_/article/details/97498160