前后分离开发主要是通过前后端接口来进行传数据,因此就要配置跨域访问。对于新手来说,跨域设置可能是个让人头痛的问题。
因此,我这里主要贴一下前端vue项目及服务器端的跨域配置。
vue项目跨域配置:
config>index.js>proxyTable:
proxyTable: {
'/api': {
target:'http://10x.xx.xx.x1', // api服务器的ip地址或域名
changeOrigin:true, // 允许跨域请求
pathRewrite:{
'^/api': ''
}
},
'/github': {
target: 'http://10x.xx.xx.x1', // api服务器的ip地址或域名
changeOrigin: true,
pathRewrite: {
'^/github': ''
}
},
'/scnuapi': {
target: 'http://10x.xx.xx.x1', // api服务器的ip地址或域名
changeOrigin: true,
pathRewrite: {
'^/scnuapi': ''
}
},
'/reboot': {
target: 'http://10x.xx.xx.x1', // api服务器的ip地址或域名
changeOrigin: true,
pathRewrite: {
'^/reboot': ''
}
},
},
注意这个配置后,要重新编译项目,不会自动编译生效的!!!
服务器端 nginx
vue项目打包后放到nginx项目html中
设置nginx>conf>nginx.conf : http{ server{ (定位)
listen 80; // nginx服务器监听的端口
server_name localhost 127.0.0.1(服务器ip);
client_max_body_size 2G;#解决上传文件过大
charset utf-8;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, OPTINS, HEAD';
}
location /api {
#修正uri
rewrite ^/api/(.*) /$1 break;
#后端服务地址
proxy_pass http://10x.xx.xx.xx;// 服务器ip
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, OPTINS, HEAD';
}
location /github {
#修正uri
rewrite ^/github/(.*) /$1 break;
#后端服务地址
proxy_pass https://github.com;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, OPTINS, HEAD';
}
location /scnuapi {
#修正uri
rewrite ^/scnuapi/(.*) /$1 break;
#后端服务地址
proxy_pass http://10x.xx.xx.xx;// 服务器ip
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, OPTINS, HEAD';
}
location /reboot {
#修正uri
rewrite ^/reboot/(.*) /$1 break;
#后端服务地址
proxy_pass http://openapi.tuling123.com;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, OPTINS, HEAD';
}
注意配置这个后一定要重启nginx, 因为nginx没有明显的重启按钮,所以如果不行,试着关机试试,哈哈哈哈~~~~
以上就是前后端分离的前端部署,如果还不清楚,可以下载下面的文件仔细看看。
这个前端项目跟下面这个后端java是配套的
web前后端分离开发——后端SpringMVC java开发
里面有个图灵机器人没有删,各位不要乱掉我的图灵机器人接口,否则我会删资源的。