简体   繁体   中英

How to extract body from request with express in NodeJs?

I'm using Node.Js and express framework for my application.

I build HTML forms and upon submitting I'm not able to receive my form data on API request.

My HTML:

<form method="post" action="/create">
    <input type="text" name="user.name" />
    <input type="text" name="user.email" />
    <input type="text" name="user.address.city" />
    <input type="text" name="user.address.land" />
    <input type="submit" value="Submit">
</form>

JSON object should been obtained at my API:

{
   "user": {
      "name": "toto",
      "email": "toto@mail.com",
      "address": {
         "city": "yyyyy",
         "land": "zzzz"
      }
   }
}

How to do this with Node.js, Express 4 and is there another library for this?

You can prepare your own middleware that parses the incoming form data using body-parser's urlencoded() and turns it into a structured JSON:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

function setDeepValue(path, obj, value) {
  const tokens = path.split('.');
  const last = tokens.pop();
  for (const token of tokens) {
    if (!obj.hasOwnProperty(token)) {
      obj[token] = {};
    }
    obj = obj[token];
  }
  obj[last] = value;
}

app.use(bodyParser.urlencoded(), function(req, res, next) {
  let obj = {};
  for (const key in req.body) {
    setDeepValue(key, obj, req.body[key]);
  }
  req.body = obj;
  next();
});

app.post('/create', function(req, res) {
  console.log(req.body)
})

In your HTML code you are posting to a create route.

So in express you need to create that route

const express = require('express')
const bodyParser = require('body-parser')
const app = express()

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

app.post('/create', function(req, res) {
  console.log('----- MY BODY -----')
  console.log(req.body)
  // do something more clever
  res.send('We posted to this route')
})

First we require express, then we require body-parser and finally initialize our express app.

We then use the json middlewere of body-parser to parse the body so that we can easily access it in our handler.

We then define a route to '/create' that accepts posts request (remember that your form is posting to this location).

All that our handler does is to console.log the body of the request, and then shows the message We posted to this route

Follow this guide repository specially created to guide freshers nodejs-frontend-sample-for-freshers

EDIT:

You can use Ajax call to submit form this will also help in Single Page Application

Client-side JS:

function submit() {
    // JavaScript uses `id` to fetch value
    let email               = $("#email").val(),
        name                = $("#name").val(),
        city                = $("#city").val(),
        land                = $("#land").val();

    // Can validate each field here and show error like:
    if ( validateEmail(email) ) {
        $("#emailError").addClass("hide");
    } else {
        $("#emailError").removeClass("hide");
        return;
    }

    // form request data, doing this will get you data in correct form at NodeJs API
    let data = {
        user: {
            email,
            name,
            address: {
                city,
                land
            }
        }
    };

    $.ajax({
        "url": "/create",
        "method": "POST",
        "data": data
    })
    .then( result => {
        // On success empty all the input fields.
        $("#email").val('');
        $("#name").val('');
        $("#city").val('');
        $("#land").val('');

        // Message to notify success submition
        alert("Successfully added user.");
        return;
    })
    .catch( err => {
        // Notify in case some error occured
        alert("An error occured.");
        return;
    });
}

// Validate Email based upon pattern
function validateEmail (email) {
    if ( email && email.match(/^([A-z0-9_.]{2,})([@]{1})([A-z]{1,})([.]{1})([A-z.]{1,})*$/) ) {
        return true;
    }
    return false;
}

HTML:

<form>
    <input type="text" id="name" />
    <input type="text" id="email" />
    <span id="emailError" class="hide error">Valid Email Required</span>
    <input type="text" id="city" />
    <input type="text" id="land" />
    <p onclick="submit()">Submit</p>
</form>

Would recommend you to use cors.js too like:

const cors = require('cors');

// Cross-Origin Resource Sharing
app.use(cors()); 

You can get object in two ways:

1: Using no extra module something like this

app.post('/create', function (request, response, next) {

    let body       = [];

    request.on('error', (err) => {
        console.error(err);
    }).on('data', (chunk) => {
        body.push(chunk);
    }).on('end', () => {
        body       = Buffer.concat(body).toString();
        console.log(body); // Your object
        request.body = body;  // Store object in request again

        next();
    });
}, (req, res) => {
    console.log(req.body); // This will have your object 
});
  1. Using body-parser with express :

```

// configure the app to use bodyParser() to extract body from request.
// parse urlencoded types to JSON
app.use(bodyParser.urlencoded({
    extended: true
}));

// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }));

// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }));

// parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' }));

app.post('/create', function (request, response, next) {
    console.log(request.body);  // `body-parser did what I did earlier`
});

```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM