1.开发环境
vue解决跨域问题,访问spingboot后端接口只需要一个配置
在config文件夹中的index.js文件内修改如下:
proxyTable: {
'/api': {//定义全局访问后台服务器的别名
target: 'http://localhost:8080/project',//后端服务器访问地址
changeOrigin: true,//如果跨域就是true
//secure: true, // 如果是https接口,需要配置这个参数
pathRewrite: {
//后台接口路径,如果后台接口没有统一的前缀(/api)就用第一个
//有统一前缀就用第二个(前缀是什么就写什么)
'^/api': '/'
// '^/api': '/api'
}
}
}
2.正式生产环境
上述proxyTable可以不写,只需要修改nginx.conf的配置,如下
server {
listen 9001;#监听9001端口,可以改成其他端口
server_name localhost;# 当前nginx服务的域名
root D:/node_project/myVue/dist;#vue项目的打包后的dist文件目录
location / {
try_files $uri $uri/ @router;#需要指向下面的@router否则会出现vue的路由在nginx中刷新出现404
index index.html index.htm;
}
#对应上面的@router,主要原因是路由的路径资源并不是一个真实的路径,所以无法找到具体的文件
#因此需要rewrite到index.html中,然后交给路由在处理请求资源
location @router {
rewrite ^.*$ /index.html last;
}
location /api{//定义vue前端访问后台服务器的别名
//*特殊注意proxy_pass不能写成http://localhost:8080,必须加一个访问路径要不然报404
proxy_pass http://localhost:8080/project; /后端服务器访问地址 ,如果localhost不好使请改成127.0.0.1
proxy_set_header Host $host;
proxy_set_header x-forwarded-for $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
axios get请求
this.$axios.get('/api/后端接口', {
params: {
name: 'wm' //可选
}
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
}).then(function () {
// always executed
});
axios post请求
this.$axios.post('/api/后端接口', {
name: 'wm' //可选
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
}).then(function () {
// always executed
});