工作中我们经常遇到需要后端接口,可是我们前后端都是同时开发的,接口不一定能在我们需要的时候就提供给我们。这就需要我们前端同学自力更生写模拟数据了。下面介绍两种偷懒的方法。
第一种解决办法
1、安装nginx并把nginx.conf改动下配置
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
proxy_pass http://localhost:3000;
index index.html index.htm;
}
location ~ \.json$ {
root html;
index index.html index.htm;
}
}
复制代码
以上配置能够达到,访问http://localhost:80下的资源会转到3000端口,访问80下的json会转到nginx默认的html文件夹下资源。
但是有缺点就是页面无法实时刷新。
第二种解决办法
1、一个文件夹比如src1228使用gulp开启服务http://localhost:3000做后端接口
2、一个文件夹比如src中做正常开发,gulp开启做实时刷新和代理,代理到http://localhost:3000做后端接口。
var gulp = require('gulp'),
connect = require('gulp-connect'),
proxy = require('http-proxy-middleware'),
livereload = require('gulp-livereload'),
watch = require('gulp-watch');
//定义看守任务
gulp.task('watch', function() {
// Create LiveReload server
livereload.listen();
// Watch any files in dist/, reload on change
gulp.watch(['./**']).on('change', livereload.changed);
})
gulp.task('connect', function() {
connect.server({
/*根路径*/
root: './',
/*开启浏览器自动刷新*/
livereload: true,
/*端口号*/
port: 8080,
/*IP*/
host:'10.10.92.32',
/*使用代理服务*/
middleware: function(connect, opt) {
return [
proxy('/api', {
target: 'http://localhost:3000/',
changeOrigin: true,
pathRewrite: {
'^/api/': '' // rewrite path
}
})
]
}
});
});
gulp.task('default', gulp.parallel('connect', 'watch'));
//使用代理后访问http://localhost:8080/api/data.json会转到http://localhost/data.json
//安装gulp-livereload后有的文章说需要在浏览器装个liveload的扩展。
//我安装后又卸载了还是可以正常使用,如果不能正常使用,大家可以试下装下这个扩展。
复制代码