Angular/Gulp 应用程序的模拟后端 [英] Mock backend for Angular / Gulp app

查看:14
本文介绍了Angular/Gulp 应用程序的模拟后端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过提供 json 响应而不依赖于真正的后端来模拟后端以加快开发速度.前端应用程序是一个 Angular 应用程序,我们使用 Gulp 作为开发和构建工具.

I would like to mock the backend for quicker development by providing json response without reling on the real backend. The frontend app is an Angular app and we use Gulp as a development and build tool.

例如有一个特定的 api (.../custumers/123) 返回一个静态 json 结果.

E.g. have a specific api (.../custumers/123) return a static json result.

是否可能已经有一个 gulp 工具来解决这个问题?

Is there perhaps already a gulp tool for this?

推荐答案

我选择了 json-servergulp-json-srv 我认为这有一些简单和快速设置.

I went with json-server and gulp-json-srv which I think had some benefits of simplicity and quick setup.

gulpfile.js 配置启动 json-server 并使用gulp mock"任务代理 http 调用:

gulpfile.js config to start json-server and to proxy the http calls using a "gulp mock" task:

gulp.task('mock', ['connect-mock'], function () {
    jsonServer.start({
        data: 'db.json',
        port: 8087
    });
});

gulp.task('connect-mock', function () {
    connect.server({
        port: 8085,
        livereload: true,
        middleware: function (connect, o) {
            return [(function () {
                var url = require('url');
                var proxy = require('proxy-middleware');
                var options = url.parse('http://127.0.0.1:8087');
                options.route = '/v2';
                return proxy(options);
            })()];
        }
    });
});

带有模拟数据的db.json:

db.json with mocked data:

{
    "customers": [
        { "id": 1, "name": "Johnny B" },
        { "id": 2, "name": "Steve G" },
        { "id": 3, "name": "Glenn H" }
    ]

这篇关于Angular/Gulp 应用程序的模拟后端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆