使用 Sails.js Generate 创建 API 非常容易。获取this tutorial example ,运行
curl -X GET http://localhost:1337/employee/1
返回
{
"id": 1,
"name": "John Smith",
"email" "john@email.com",
"empnum" "123",
"createdAt" "2015-10-25T19:25:16.559Z",
"updatedAt" "2015-10-25T19:25:16.559Z",
}
和
curl -X GET http://localhost:1337/employee/1?fields=name
会返回
{
"name": "John Smith"
}
如何配置 Sails.js 来解析子资源路径,而不是传递字段数组,如下所示:
curl -X GET http://localhost:1337/employee/1/name
最佳答案
您需要添加自定义路由和 Controller 功能,例如:
config/routes.js:
"GET /employee/:id/:field": "EmployeeController.findOneFiltered"
api/controllers/EmployeeController.js
findOneFiltered: function(req, res) {
var id = req.param("id");
var field = req.param("field");
// Fetch from database by id
Employee.findOne(id)
.then(function(employee) {
// Error: employee with specified id not found
if (!employee) {
return res.notFound();
}
// Error: specified field is invalid
if (typeof employee[field] === "undefined") {
return res.badRequest();
}
// Success: return attribute name and value
var result = {};
result[field] = employee[field];
return res.json(result);
})
// Some error occurred
.catch(function(err) {
return res.serverError({
error: err
});
});
}
关于javascript - 如何自动解析 Sails.js 路由上的模型属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40809993/