我一直在尝试为使用 yeoman
生成的应用程序创建 api stub 。 .这里没什么特别的,我只是调用:
mkdir demo1
cd demo1
yo angular
出于开发目的,我需要 api stub ,到目前为止我发现的唯一模块是 lineman .然而,据我所知,lineman 并不是对 yeoman 非常友好,所以我所做的是在端口
8000
上启动 lineman ,提供一些 api stub (如文档中的 stub ),并添加 "grunt-connect-proxy": "~0.1.5"
投影节点模块,然后创建一个代理,通过所有 localhost:9000/api/*
至localhost:8000/api/*
,从而提供 stub 。虽然这可行,但我想删除 lineman 依赖项并自己提供 stub 。这是我到目前为止写的代码(添加了
express
作为路由/参数解析的依赖项) - 大部分代码是来自 express 模块的点点滴滴,以便包装 http.ServerRequest
和 http.ServerResponse
进 express request
& response
:// load all grunt tasks
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
var drawRoutes = require('./config/server').drawRoutes;
var express = require('express');
var expressApp = express();
drawRoutes(expressApp);
var router = expressApp._router;
// Provide api stubs through express router functionality.
var apiStubSnippet = function(req, res, next) {
var match = router.matchRequest(req);
if (typeof(match) !== 'undefined') {
// Found a match, invoke it
if (match.callbacks.length > 0) {
var _req = require('express/lib/request');
var _resp = require('express/lib/response');
// Set the two objects together ... but why?!
_req.__proto__ = req;
_req.app = expressApp;
_req.res = _resp;
_resp.__proto__ = res;
_resp.app = expressApp;
_resp.req = _req;
match.callbacks[0](_req, _resp);
}
} else {
// No match on the router, go next.
next();
}
};
此时,调用似乎已解决(控制台中不再出现错误)。但是,电话一直待定,我不知道如何进行。我很确定代码对于它需要做的事情来说过于复杂,但我是 grunt 和节点模块的初学者。
任何帮助都可以,谢谢。
最佳答案
Angular 允许您使用 $httpBackend
stub ,你试过这个吗?
我喜欢尽可能地打破 JS 最佳实践,所以这是我今年早些时候为一个项目所做的事情:
app.run(function ($httpBackend) {
var createResponse = function (type, url, status, response) {
var when = $httpBackend.when(type, url);
if (angular.isDefined(status) && angular.isDefined(response))
when.respond(status, response);
return when;
};
String.prototype.get =
RegExp.prototype.get = function (status, response) { return createResponse('GET', this, status, response); };
String.prototype.post =
RegExp.prototype.post = function (status, response) { return createResponse('POST', this, status, response); };
String.prototype.put =
RegExp.prototype.put = function (status, response) { return createResponse('PUT', this, status, response); };
/^\/views\//
.get()
.passThrough();
'/api/login'
.post(200, {
// response object.
});
});
这种特殊的方法可能不是您想要的,但是
$httpBackend
可能是。
关于gruntjs - 在 yeoman 生成的应用程序中为 API 调用提供 stub ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17541350/