在node.js中实现RESTful API

时间:2014-01-25 18:25:06

标签: node.js rest

我有以下假设的RESTful API端点:

/courses
/courses/:id
/students
/students/:id
/courses/:c_id/students
/courses/:c_id/students/:s_id
/students/:s_id/courses
/students/:s_id/courses/:c_id

你如何编码node.js中的路由(我使用express),这样你可以减少重复的代码和路由(特别是在学生和课程的多对多关系中)?

蛮力方法的一个例子是:

app.get('/courses', courses.getAll);
app.post('/courses', courses.create);
app.get('/courses/:id', courses.get);
app.put('/courses/:id', courses.edit);
app.del('/courses/:id', courses.delete);
...
app.get('/courses/:c_id/students', courseStudents.getStudents);
app.get('/courses/:c_id/students/:s_id', courseStudents.getStudent);
...
app.get('/students/:s_id/courses', studentCourses.getCourses)
app.get('/students/:s_id/courses/:c_id', studentCourses.getCourse)
...

1 个答案:

答案 0 :(得分:0)

我建议尝试loopback,它基于express.js,专为REST API而设计。

这是一个例子:https://github.com/strongloop/loopback-example-full-stack