node - 怎样同时启动gulp和json-server服务?
本文介绍了node - 怎样同时启动gulp和json-server服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
项目里已经安装了gulp,启动服务,可以访问静态文件html,但是很多接口调用,想用json-server模拟接口,但是我想把这两个功能同时启动,
或者把json-server集成到gulp中,或者能够同时启动这两个服务,并且在同一个端口下,这个是重点,必须是同一个端口,不然接口调用就跨域了。
该如何操作呢?
解决方案
同一个端口,肯定不行。
给你一个方案 用 http-proxy-middleware 加代理,在gulp中 child_process 起一个进程去跑 json-server, 下面代码是实际项目中的代码片段
...
var proxyMiddleware = require('http-proxy-middleware');
var child = require('child_process');
...
...
...
gulp.task('dev:browser-sync', function(){
//add proxy for gui
var middleware = proxyMiddleware(['/user', '/persons'], {target: 'http://localhost:9001', changeOrigin: true});
browserSync({
server: {
baseDir: './',
index: 'build/login.html',
middleware: middleware
}
});
});
gulp.task('dev:copy', ['dev:copy-html', 'dev:copy-conf', 'dev:copy-login', 'dev:copy-data']);
gulp.task('dev', 'Run this for developing', ['dev:index', 'dev:copy', 'dev:browser-sync', 'dev:watch-files'], function(){
//json-server --watch server/db.json --port 9001
var jsonServer = child.spawn('node_modules/json-server/bin/index.js', ['--watch', 'server/db.json', '--port', '9001']);
jsonServer.stdout.on('data', function (data) {
fs.writeFileSync("log/json-server.log", data.toString());
});
jsonServer.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
jsonServer.on('exit', function (code) {
console.log('child process exited with code ' + code);
});
});
再给你个方案:
用 concurrently 方法去启动两个命令, 然后在gulp中把代理加上
"dev": "concurrently \"gulp dev\" \"nodemon mock-server.js\"",
这个方案可以参考 https://github.com/hjzheng/gulp-AngularJS1.x-seed
这篇关于node - 怎样同时启动gulp和json-server服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文