سؤال

I am pretty new to networks and web stuff. I was going through a book, and there was this code.

app.post('/send', app.use(bodyParser()), function(req,res){
if(req.body && req.body.postex){
    post.push(req.body.postex)
    res.send({status:"ok", message:"Post received"})
}
})

I did not get where the postex field/property came from. Aren't requests things that are already set. The code provided did not initilize postex and then suddenly wrote it down. I am pretty confused about it. Can you explain me what is going on here ?

هل كانت مفيدة؟

المحلول

In this case, you might find it useful to read a little bit about Representational State Transfer (REST) as outlined here, and the different HTTP methods, outlined here.

Roughly, a POST method, as shown by

app.post('/send', app.use(bodyParser()), function(req,res){

is a way to send some form of data to your web server. In this case, your web server is Express, and the data you've sent to this route is contained within your request object req.

This data will likely have been filled in by a user typing into a web form, and the names of your form elements on your web page will correspond to attributes inside your req object, specifically inside req.body as @disklosr pointed out.

For example, let's say you have the following form on your page.

<form action="/send" method="post">
  <input name="say" value="Hi">
  <input name="to" value="Mom">
  <button>Send my greetings</button>
</form>

Accessing your req.body object would show you something like

{
  say: "Hi",
  to: "Mom"
}

i.e.

console.log(req.body.say);
> "Hi"

In your case, there will be a form field with a name attribute titled postex. The value of which will be sent to your server when the form values are submitted, which should then be accessed in your server-side code via req.body.postex.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top