问题描述:因为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
解决:
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:

"target": "localhost:3000"

mac:

"target": "http://127.0.0.1:3000"

发送axios部分:

this.axios.post('/api2/users/login'

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

原文链接:https://blog.csdn.net/reagan_/article/details/97498160

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐