Giter Site home page Giter Site logo

Comments (12)

dougwilson avatar dougwilson commented on April 20, 2024

That works just fine for me. Can you provide some more details, like what isn't working, or what the error is, or what the parse looks like to you?

from body-parser.

charyorde avatar charyorde commented on April 20, 2024

console.log(req.body) simply returns {}.
The full route looks like this:

var router = express.Router();
var validator = require('express-validator');
router.use(validator());

var jsonParser = bodyParser.json({ type: 'application/*+json' } );

router.post('/create-account', jsonParser, function(req, res) {
  console.log(req.body); // This returns {}
  if (!req.body) return res.sendStatus(400);

  req.checkBody('userName', 'required').notEmpty();
  req.checkBody('name', 'required').notEmpty();

  var errors = req.validationErrors();
  if (errors) {
    res.status(400).send('There have been validation errors: ' + util.inspect(errors));
    return;
  }

I know body-parser has nothing to do with validation(used express-validator), but since you asked for details, on validation, the json fields couldn't be validated because req.body returns empty.

There have been validation errors: [ { param: 'userName', msg: 'required', value: undefined }, { param: 'name', msg: 'required', value: undefined }]

from body-parser.

dougwilson avatar dougwilson commented on April 20, 2024

Gotcha. It would seem the reason req.body = {} for your case is because of one of two reasons (both of which I cannot confirm because will app code wasn't pasted):

  1. The request's content-type is not application/stuff+json; if it is just application/json then your jsonParser will ignore it
  2. The jsonParser you have there will only ever work as long as something prior to your code is not reading the bdoy, as in perhaps somewhere outside what you posted there is a app.use(bodyParser) or similar?

The following code works perfectly fine for me:

var app = express();
var router = express.Router();

var jsonParser = bodyParser.json({ type: 'application/*+json' } );

router.post('/create-account', jsonParser, function(req, res) {
  console.log(req.body);
});

app.use(router);
app.listen(3000);

from body-parser.

charyorde avatar charyorde commented on April 20, 2024

Thanks

I don't have app.use(bodyParser()) anywhere in my code. Moreso, I'm reading the json data from a file like so:

curl -v -H "Content-Type: application/json" -d @/tmp/create-account.json http://localhost:3000/auth/create-account

Could it be that there's something wrong with how the request is constructed? What's your request content-type?

from body-parser.

dougwilson avatar dougwilson commented on April 20, 2024

Could it be that there's something wrong with how the request is constructed?

Ah. Your cURL command has the wrong content type, as application/json does not match application/*+json. You need to change one or the other. If you want to use application/json, then set that in your code, otherwise send a content-type in cURL that matches application/*+json.

What's your request content-type?

I used application/stuff+json as stated above.

from body-parser.

charyorde avatar charyorde commented on April 20, 2024

Okay. I simply changed the request to curl -v -d @/tmp/create-account.json http://localhost:3000/auth/create-account and code as:

var urlencodedParser = bodyParser.urlencoded({extended: false } );

router.post('/create-account', urlencodedParser, function(req, res) {
  console.log(req.body);
});

from body-parser.

charyorde avatar charyorde commented on April 20, 2024

Well, just for enhancement purposes for the library, a request like so:
curl -v -H "Content-Type: application/json" -d @/tmp/create-account.json http://localhost:3000/auth/create-account and code like so:

var jsonParser = bodyParser.json({ type: 'application/json' } );
router.post('/create-account', jsonParser, function(req, res) { 
  console.log(req.body)
});

gives this error:

SyntaxError: Unexpected token }
    at Object.parse (native)
    at parse (/Users/osx/projects/nodescripts/useraccountservice/node_modules/body-parser/lib/types/json.js:84:17)
    at /Users/osx/projects/nodescripts/useraccountservice/node_modules/body-parser/lib/read.js:102:18
    at IncomingMessage.onEnd (/Users/osx/projects/nodescripts/useraccountservice/node_modules/body-parser/node_modules/raw-body/index.js:136:7)
    at IncomingMessage.g (events.js:180:16)
    at IncomingMessage.emit (events.js:92:17)
    at _stream_readable.js:943:16
    at process._tickCallback (node.js:419:13)

from body-parser.

dougwilson avatar dougwilson commented on April 20, 2024

It's because you're sending invalid JSON.

from body-parser.

dougwilson avatar dougwilson commented on April 20, 2024

Feel fee to post the contents of /tmp/create-account.json and I can point out where the JSON is invalid (you can always check yourself by running the file through JSON.parse, part of core JavaScript.

from body-parser.

charyorde avatar charyorde commented on April 20, 2024
{
    "schemas":["urn:scim:schemas:core:1.0"],
    "userName":"bjensen",
    "name":{
        "formatted":"Ms. Barbara J Jensen III",
        "familyName":"Jensen",
        "givenName":"Barbara"
    },
    "emails":[{
        "type":"home",
        "value":"[email protected]"
    }],
}

from body-parser.

dougwilson avatar dougwilson commented on April 20, 2024

That very last trailing comma is illegal is JSON.

from body-parser.

charyorde avatar charyorde commented on April 20, 2024

Awesome. Merci!

from body-parser.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.