Express Framework app.post and app.get

7

我对express框架还比较陌生。在express API参考文档中找不到application.post()方法的文档。能否有人提供一些可以放入该函数的所有可能参数的示例?我已经阅读了几个网站,其中有以下示例,第一个参数是什么意思?

  1. I know the second parameter is the callback function, but what exactly do we put in the first parameter?

    app.post('/', function(req, res){
    
  2. Also, let's say we want the users to post(send data to our server) ID numbers with a certain format([{id:134123, url:www.qwer.com},{id:131211,url:www.asdf.com}]). We then want to extract the ID's and retrieves the data with those ID's from somewhere in our server. How would we write the app.post method that allows us to manipulate the input of an array of objects, so that we only use those object's ID(key) to retrieve the necessary info regardless of other keys in the objects. Given the description of the task, do we have to use app.get() method? If so, how would we write the app.get() function?

非常感谢你的输入。
2个回答

7

1. app.get('/', function(req, res){
这告诉Express监听请求到/,并在看到请求时运行该函数。

第一个参数是要匹配的模式。有时是像'/''/privacy'这样的字面URL片段,您还可以使用以下示例中所示的替换符号。如果需要,还可以像此处描述的那样匹配正则表达式。

Express的所有内部组件都遵循function(req, res, next)模式。传入的请求从中间件链的顶部开始(例如bodyParser),并沿着链路传递,直到某些内容发送响应,或者express到达链的末尾并返回404错误。

通常将app.router放在链的底部。当Express到达那里时,它开始按照设置的顺序匹配所有的app.get('path'...app.post('path'...等请求。

变量替换:

// this would match:
// /questions/18087696/express-framework-app-post-and-app-get

app.get('/questions/:id/:slug', function(req, res, next){
  db.fetch(req.params.id, function(err, question){
    console.log('Fetched question: '+req.params.slug');
    res.locals.question = question;
    res.render('question-view');
  });
});

next():
如果您将处理函数定义为function(req, res, next){},则可以调用next()来暂停执行,并将请求传递回中间件链。例如,对于一个捕获所有路由的情况,您可能会这样做:

app.all('*', function(req, res, next){
  if(req.secure !== true) {
    res.redirect('https://'+req.host+req.originalUrl);
  } else {
    next();
  };
});

再次强调,顺序很重要,如果你想让它在其他路由函数之前运行,你必须把它放在它们的上面。

我以前没有POST过JSON,但@PeterLyon的解决方案对我来说看起来很好。


6
TJ在express文档中令人烦恼地将其记录为app.VERB(path, [callback...], callback,因此请在express文档中搜索此内容。我不会在这里复制/粘贴它们。 这是他不友善的方式来说明app.getapp.postapp.put等都具有相同的函数签名,并且每种受支持的HTTP方法都有其中一种方法。
要获取已发布的JSON数据,请使用bodyParser中间件:
app.post('/yourPath', express.bodyParser(), function (req, res) {
  //req.body is your array of objects now:
  // [{id:134123, url:'www.qwer.com'},{id:131211,url:'www.asdf.com'}]
});

这个语法是我描述的中间件链的另一个例子!express.bodyParser()返回一些带有签名function(req, res, next)的函数,并在将json解析为req.body对象后内部调用next()。然后,Express将请求传递到中间件链的下一个环节,即app.post('/yourPath', ...)的第三个参数,这是Peter编写的函数。 - Plato
嗨,我正在尝试在Express文档中找到app.get!感谢你的app.VERB评论。 - zastrowm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接