【Gulp】gulp和JsonSever结合模拟数据

前言

        本来呢?研究这个课题的目的是让gulp自动返回模拟的后台数据,但是还没有做出来,仅仅出来个中间效果,告别F5时代的HTML页。

gulpfile.js

'use strict';
var gulp = require('gulp'),
    less = require('gulp-less'),
    connect = require('gulp-connect'),
    port = 5000;//访问的端口
var rename = require('gulp-rename');
var plumber = require('gulp-plumber'); // 错误处理插件
var notify = require('gulp-notify'); // 消息插件
var autoprefixer = require('gulp-autoprefixer'); // 自动添加前缀
var minifycss = require('gulp-minify-css');
var proxy = require('http-proxy-middleware');
gulp.task('server',function(){
    connect.server({
        root:[__dirname],
        port:port,
        livereload:true,
        middleware:function(connect, opt){
            return [
                proxy('/api', {// configure proxy middleware
                    // context: '/' will proxy all requests
                    // use: '/api' to proxy request when path starts with '/api'
                    target: 'http://localhost:3000',
                    changeOrigin:true    // for vhosted sites, changes host header to match to target's host
                })
            ];
        }
    });
});
gulp.task('reload',function(){
    gulp.src(['./index.html', './less/style.less'])
        .pipe(connect.reload());
});

gulp.task('default',['server'],function(){
    gulp.watch(['./index.html'],['reload']);
});

HTML页

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="http://apps.bdimg.com/libs/zepto/1.1.4/zepto.min.js"></script>
</head>
<body>
<h1>gulp</h1>
<script>
    // $.get('api/profile',function(re){
    //     console.log(re);
    // })
    $.post("api/posts",{suggest:'xx'},function(re){
        console.log(re);
    });
</script>
</body>
</html>

db.json

{
  "posts": [
    {
      "id": 1,
      "title": "json-server",
      "author": "typicode"
    }
  ],
  "comments": [
    {
      "id": 1,
      "body": "some comment",
      "postId": 1
    }
  ],
  "profile": {
    "name": "typicode"
  }
}

效果

        HTML页


        修改保存后


        直接保存,无需F5刷新页面即可将结果显示出来。

总结

        虽然真正想要的结果没有出来,但在研究的过程中还是收获了很多东西的,相比之前保存页面代码后,还需要在前台刷新才能出来结果,现在能直观的展现出我们的修改,在效率与体验上也是相当有进步的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 20
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值