【发布时间】:2015-08-28 07:46:17
【问题描述】:
我正在开发一个 MEAN 堆栈应用程序,我正在尝试创建 Angular 客户端可以$http.get 的几个 API 端点,其中包含填充有虚拟数据的简单 JSON 文件。
这是我正在尝试测试的orders.json 文件:
[
{
"order_status":"Shipped",
"order_qty":30
},
{
"order_status":"Shipped",
"order_qty":6
}
]
例如$http.get的api路由:
apiRouter.get('/:fileName', queries.getStaticJSONFileForDevelopment);
但是当我尝试将 express 的 sendFile 方法与本地 .json 文件一起使用时,例如 orders.json:
queries.js:
exports.getStaticJSONFile = function(req, res) {
var fileName = req.params.fileName;
console.log('path: ' + path.normalize(__dirname + '/' + fileName));
res.sendFile(path.normalize(__dirname + '/' + fileName), function(err) {
if (err) return res.send({ reason:error.toString() });
});
};
console.log 告诉我我指向了文件的正确路径,但 Postman 提供了这个错误:
TypeError: undefined is not a function
at Object.exports.getStaticJSONFile [as handle] (path/to/queries.js:260:7)
// queries.js:260:7 points to the 's' in 'sendFile' above
但是,当我自己发送 json 数据时:
res.send([{"order_status":"Shipped","order_qty":30},{"order_status":"Shipped","order_qty":6}]);
...端点按照您的预期呈现数据。我是否试图让 sendFile 方法做一些它不应该做的事情,或者我错过了什么?非常感谢您的任何建议!
【问题讨论】:
-
您想用附加文件回答还是用 content-type: application/json 回答?也许你想读取 json 文件并输出 json 数据?