还有另一种可能性,可以在开发过程中为应用程序提供静态数据。 Navigation Skeleton 已经带有 Gulp 和 BrowserSync,所以我们用它们来伪造 API 调用。
假设您从 /api 虚拟目录加载 JSON 数据,例如
GET /api/products
在这种情况下,你只需要两件事来伪造它。
将您的模拟数据放入文件中
转到您的 Aurelia 应用程序的根文件夹并创建一个 /api 文件夹。
创建一个/api/products 子文件夹并放置一个名为GET.json 的新文件。此文件应包含 JSON,例如
GET.json
[ { "id": 1, "name": "Keyboard", "price": "60$" },
{ "id": 2, "name": "Mouse", "price": "20$" },
{ "id": 3, "name": "Headphones", "price": "80$" }
]
配置 BrowserSync 以模拟您的 API 调用
导航到/build/tasks 文件夹并编辑serve.js 文件。将服务任务的定义改为如下代码:
gulp.task('serve', ['build'], function(done) {
browserSync({
online: false,
open: false,
port: 9000,
server: {
baseDir: ['.'],
middleware: function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
// Mock API calls
if (req.url.indexOf('/api/') > -1) {
console.log('[serve] responding ' + req.method + ' ' + req.originalUrl);
var jsonResponseUri = req._parsedUrl.pathname + '/' + req.method + '.json';
// Require file for logging purpose, if not found require will
// throw an exception and middleware will cancel the retrieve action
var jsonResponse = require('../..' + jsonResponseUri);
// Replace the original call with retrieving json file as reply
req.url = jsonResponseUri;
req.method = 'GET';
}
next();
}
}
}, done);
});
现在,当您运行 gulp serve 时,BrowserSync 将处理您的 API 调用并从磁盘上的静态文件中提供它们。
您可以在我的github repo 中查看示例,在我的Mocking API calls in Aurelia 中查看更多说明。