模拟多接口数据的懒办法

工作中我们经常遇到需要后端接口,可是我们前后端都是同时开发的,接口不一定能在我们需要的时候就提供给我们。这就需要我们前端同学自力更生写模拟数据了。下面介绍两种偷懒的方法。

第一种解决办法

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的扩展。
//我安装后又卸载了还是可以正常使用,如果不能正常使用,大家可以试下装下这个扩展。
复制代码

转载于:https://juejin.im/post/5c26dda9518825314b0c0b33

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值