Javascript 使用nodeJS为restfulweb服务定义GET函数
给定一个RESTfulWeb服务,允许不同的用户发布不同的文章 用于在服务器端定义Javascript 使用nodeJS为restfulweb服务定义GET函数,javascript,node.js,rest,Javascript,Node.js,Rest,给定一个RESTfulWeb服务,允许不同的用户发布不同的文章 用于在服务器端定义GET函数 我想在服务器端应该有异步函数,比如list,gettopviewd,getTopFavorite等函数 那么下面的说法正确吗? exports.get = function(req, res) { db.articles.list(function etc) db.articles.getTopViewed(function etc) db.articles.getTopFav
GET
函数
我想在服务器端应该有异步函数,比如list
,gettopviewd
,getTopFavorite
等函数
那么下面的说法正确吗?
exports.get = function(req, res) {
db.articles.list(function etc)
db.articles.getTopViewed(function etc)
db.articles.getTopFavorite(function etc)
}
注意:在另一个JavaScript文件中定义了列表
、getTopViewed
和getTopFavorite
在另一个JS文件中:
exports.list = function(callback){
// acts as async callback
var result = ArticleModel.find({}, function(err, articles){
callback(null, articles)
});
return result;
}
我建议使用类似或。它有一个路由器,使这一点更容易。设置和用法如下所示:
var express = require("express"),
db = require('./yourdb.js');
var app = express.createServer();
app.configure(function(){
app.use(app.router);
});
app.get("/articles/", function(req, res){
db.list(function(err, articles){
res.writeHead(200);
// you probably want to do something more complex here
res.end(JSON.stringify(articles));
});
});
app.get("/articles/top", function(req, res){
// res.end(<top articles go here>);
});
var express=require(“express”),
db=require('./yourdb.js');
var app=express.createServer();
app.configure(函数(){
应用程序使用(应用程序路由器);
});
app.get(“/articles/”,函数(req,res){
数据库列表(函数(错误、文章){
书面记录(200);
//你可能想做一些更复杂的事情
res.end(JSON.stringify(articles));
});
});
app.get(“/articles/top”),函数(请求,res){
//res.end();
});
这里是指向Express路由器文档的链接:您需要提供更多上下文。这些方法是同步的吗?如果没有,则需要类似于
async
模块的功能。你还需要在某个时刻做出回应。顺便说一句,如果它能正常工作,它通常是正确的。我使用mongoose和Express。我可以知道使用export.get=function(req,res)
和使用app.get(“/articles/top”)
?exports.get
在名为get
的模块中定义一个函数吗。当您使用require
包含另一个js文件时,可以使用此选项。它是节点模块系统的一部分