当前位置: 代码迷 >> 综合 >> 【Gulp】gulp和JsonSever结合模拟数据
  详细解决方案

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

热度:48   发布时间:2024-01-14 10:28:40.0

前言

        本来呢?研究这个课题的目的是让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刷新页面即可将结果显示出来。

总结

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