node.js Express 框架 app.post 和 app.get

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18087696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:12:44  来源:igfitidea点击:

Express Framework app.post and app.get

node.jssyntaxparametersexpressurl-parameters

提问by jensiepoo

I am fairly new to the express framework. I couldn't find the documentation for application.post() method in the express API reference. Can someone provide a few examples of all the possible parameters I can put in the function? I've read a couple sites with the following example, what does the first parameter mean?

我对快速框架相当陌生。我在 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?

  1. 我知道第二个参数是回调函数,但是我们在第一个参数中到底放了什么?

    app.post('/', function(req, res){
    
  2. 另外,假设我们希望用户发布(将数据发送到我们的服务器)具有特定格式的 ID 号([{id:134123, url:www.qwer.com},{id:131211,url:www.asdf. com}])。然后我们想要提取 ID 并从我们服务器的某个地方检索带有这些 ID 的数据。我们将如何编写允许我们操作对象数组输入的 app.post 方法,以便我们只使用这些对象的 ID(key) 来检索必要的信息,而不管对象中的其他键。鉴于任务的描述,我们是否必须使用 app.get() 方法?如果是这样,我们将如何编写 app.get() 函数?

Thanks a lot for your inputs.

非常感谢您的投入。

回答by Plato

1. app.get('/', function(req, res){
This is telling express to listen for requests to /and run the function when it sees one.

1.app.get('/', function(req, res){
这是告诉 express 侦听请求/并在它看到一个函数时运行该函数。

The first argument is a pattern to match. Sometimes a literal URL fragment like '/'or '/privacy', you can also do substitutions as shown below. You can also match regexes if necessary as described here.

第一个参数是要匹配的模式。有时像'/'或这样的文字 URL 片段'/privacy',您也可以进行如下所示的替换。如有必要,您还可以按照此处所述匹配正则表达式。

All the internal parts of Express follow the function(req, res, next)pattern. An incoming request starts at the top of the middleware chain (e.g. bodyParser) and gets passed along until something sends a response, or express gets to the end of the chain and 404's.

Express 的所有内部部件都遵循该function(req, res, next)模式。传入的请求从中间件链的顶部开始(例如bodyParser)并一直传递,直到某些东西发送响应,或者 express 到达链的末端和 404。

You usually put your app.routerat the bottom of the chain. Once Express gets there it starts matching the request against all the app.get('path'..., app.post('path'...etc, in the order which they were set up.

你通常把你的app.router放在链条的底部。一旦快递到达那里它开始匹配对所有的请求app.get('path'...app.post('path'...等等,它们被设置顺序。

Variable substitution:

变量替换:

// 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():
If you defined your handling functions as function(req, res, next){}you can call next()to yield, passing the request back into the middleware chain. You might do this for e.g. a catchall route:

next()
如果您定义了function(req, res, next){}可以调用next()yield 的处理函数,则将请求传递回中间件链。例如,您可以为一个包罗万象的路线执行此操作:

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

Again, order matters, you'll have to put this above the other routing functions if you want it to run before those.

同样,顺序很重要,如果您希望它在其他路由功能之前运行,则必须将其置于其他路由功能之上。

I haven't POSTed json before but @PeterLyon's solution looks fine to me for that.

我之前没有发布过 json,但 @PeterLyon 的解决方案对我来说看起来不错。

回答by Peter Lyons

TJ annoyingly documents this as app.VERB(path, [callback...], callbackin the express docs, so search the express docs for that. I'm not going to copy/paste them here. It's his unfriendly way of saying that app.get, app.post, app.put, etc all have the same function signature, and there are one of these methods for each supported method from HTTP.

TJapp.VERB(path, [callback...], callback在 express 文档中烦人地记录了这一点,因此请搜索 express 文档。我不会在这里复制/粘贴它们。这是他不友好的说法app.getapp.post, app.put, 等都具有相同的函数签名,并且每个支持的 HTTP 方法都有这些方法之一。

To get your posted JSON data, use the bodyParsermiddleware:

要获取您发布的 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'}]
});