How to get data passed from a form in Express (Node.js)

前端 未结 3 1662
挽巷
挽巷 2020-12-04 20:59

I would like to get data that are passed from a page using a form and use that data in the page that is redirected.

I have this form in my client side:



        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 21:31

    Use bodyParser.urlencoded() middleware:

    const bodyParser = require('body-parser');
    app.use(bodyParser.urlencoded({ extended: true }));
    

    Then the form values will be on req.body:

    app.post('/game', function (req, res) {
        res.render('the_template', { name: req.body.name });
    });
    

    Setting { extended: true } allows the bodyParser to accept json like data within the form data including nested objects. e.g. { person: { name: Adam } } sent using javascript rather than the name value pairs which traditional HTML form send. If you don't need that you can set the extended value to false. Not defining an extended option (i.e. using a default setting) is apparently deprecated and they seem to want you to decide whether you need nested options or plain name value pairs.

    If you want to be able to parse form data for some routes and json data for others in your express server, you can use:

    app.use(bodyParser.json())
    app.use(bodyParser.urlencoded({ extended:  }))
    

    urlencoded() for x-www-form-urlencoded content type

    • true - for nested data structures
    • false - for name value pairs

    json() - for application/json content type

    Note that form/multipart needs a different body parser (such as multer)

提交回复
热议问题