您的位置:首页 > 运维架构 > Nginx

全栈开发:前后端分离配置篇(vue+webpack+mock+nginx+laravel)

2017-08-22 11:36 4143 查看
是如何使前后端完全分离,答案是在服务器端利用nginx做转发,前端文件单独部署到服务器某目录下,nginx负责提供入口和接口监听,也就是前后端分离成两个项目部署到服务器上,好处是前端人员可以自行运维前端项目,后端人员只需要提供api接口即可,互不干扰。其实这种方案老早之前就已经被使用过了,由于入行时间不长,我在这里只是记录下自己研究的一些心得,欢迎批评指正。

下面说一下具体玩法,前端使用vue-cli搭建项目,webpack打包,在后端接口未完成情况下用mock模拟假数据,使用nginx转发接口,后端使用spring框架。

本地开发:

三种情况:

1、后端接口未完成,前端使用mock模拟数据(mock玩法请baidu)

2、后端接口可用,使用webpack-dev-server来启动项目

配置config/index.js 的 proxyTable参数实现转发,例:访问http://localhost:8080/api/login,请求会发送到http://localhost:9090/api/admin/login

dev: {
env: require('./dev.env'),
port: 8081,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: 'http://localhost:9090/api/admin/',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
}


3、后端接口可用,不使用webpack-dev-server来启动项目

配置conf/nginx.conf文件。listen:前端项目端口号,server_name:前端项目服务器名,location.root:npm run build到的dist文件夹,location.index:入口文件,location 路径名,proxy_pass:转发到的地址,例:本地访问http://localhost:8080/api/login,会转发到http://localhost:9090/api/admin/login(此处可设置成线上路径,即可以使用线上数据进行开发)

server {
listen       8081;
server_name  localhost;
#charset koi8-r;
#access_log  logs/host.access.log  main;
location / {
root   F:\.../vue-admin/dist;
index  index.html;
}
location ^~/api/ {
proxy_pass   http://localhost:9090/api/admin/; }
#error_page  404              /404.html;
# redirect server error pages to the static page /50x.html
#
error_page   500 502 503 504  /50x.html;
location = /50x.html {
root   html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
#    proxy_pass   http://127.0.0.1; #}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
#    root           html;
#    fastcgi_pass   127.0.0.1:9000;
#    fastcgi_index  index.php;
#    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
#    include        fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
#    deny  all;
#}
}


结语:通过一些简单的配置,可以使前后端分离开发,分别部署(服务器按上面配置好nginx.conf,npm run biuld出的dist文件传至服务器即可达到前后端单独部署)。前端人员在开发时,如果后端接口没有完成,可以先使用mock模拟接口数据,如果后端已经提供正确接口数据,使用vue-cli内置的代理或者本地架nginx服务器实现接口的转发,这样前后端只要在开发前商议好接口,就可以分别开发部署,极大提高开发效率,如果你是一名全栈开发人员,你更需要这种方式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  laravel nginx vue