Issue sending JSON data (with node request) to Express server to save to MongoDB

I am using MongoDB as the underlying database for my node / Express application. To summarize the problem I am facing, I do not know how to set up the body-parser configuration in the Express app because the server side app does not receive the full JSON sent by the client app (also node. Js app). For the most part, the client sends JSON in the request body to RESTful endpoints. The exception is the only case where the file needs to be uploaded, and since it is a multipart body, I use request and form-data to create this type of request and use multer in the server side to handle the multipart request, since body-parser does not handle such requests.

On the server side (Express) I have the following Express application configuration:

let app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

      

On the node client, I use the following code to create a JSON style JavaScript object and send it to a RESTful endpoint:

I'm having a hard time composing a client side request, node-request :

// class is a JavaScript/JSON object within scope of this code
let req = request.post({
  //headers: { 'Content-Type': 'application/json' },
  url: 'http://localhost:3000/classes',
  //form: class
  form: JSON.stringify(class)
}, function (err, resp, body) {
  if (err) {
    throw err;
  }
});

      

Note that I have tried multiple versions of the above code by explicitly specifying the content type as application/JSON

, and also using JSON.stringify

JavaScript to convert the object to JSON string. Collection MongoDB ( class

) stores the following type of document that contain foreign keys to other two collections ( subject

and student

):

{
  "_id" : ObjectId("57758f15f68da08c254ebee1"),
  "name" : "Grade 5 - Section A",
  "scores" : [{
    "studentId" : ObjectId("5776bd36ffc8227405d364d2"),
    "performance": [{
      "subjectId" : ObjectId("577694ecbf6f3a781759c54a"),
      "score" : 86,
      "maximum" : 100,
      "grade" : "B+"
    }]
  }]
}

      

The following error appears in the server logs:

Tue, 05 Jul 2016 04:34:46 GMT classReportApp:routes:classes class received from client: { _id: 577b38e65967097c25876764, scores: [] }
RangeError: Invalid status code: 0
    at ServerResponse.writeHead (_http_server.js:192:11)
    at ServerResponse.writeHead (C:\Development\classReportApp\node_modules\morgan\node_modules\on-headers\index.js:55:19)
    at ServerResponse._implicitHeader (_http_server.js:157:8)
    at ServerResponse.OutgoingMessage.end (_http_outgoing.js:566:10)
    at ServerResponse.send (C:\Development\classReportApp\node_modules\express\lib\response.js:205:10)
    at ServerResponse.json (C:\Development\classReportApp\node_modules\express\lib\response.js:250:15)
    at C:\Development\classReportApp\server-process\app.js:80:26
    at Layer.handle_error (C:\Development\classReportApp\node_modules\express\lib\router\layer.js:71:5)
    at trim_prefix (C:\Development\classReportApp\node_modules\express\lib\router\index.js:310:13)
    at C:\Development\classReportApp\node_modules\express\lib\router\index.js:280:7
    at Function.process_params (C:\Development\classReportApp\node_modules\express\lib\router\index.js:330:12)

      

which is weird, because the subdocument array has an empty ( scores: []

), whereas on the client side I am sending a non-empty array with some students' items in it.

Am I breaking the correct way to publish JSON apps for Express? How to fix it?

Edited: 7/5/2016 I changed the configuration of the middle body analyzer to use extended: true

instead.

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

      

node.js still uses the node-request module to compose and send a POST request using the following code

let req = request({
  url: 'http://localhost:3000/classes',
  method: 'POST',
  json: class
}, function (err, resp, body) {
  if (err) {
    throw err;
  }
  else {
    // process response
  }
});

      

This works now, but what confuses me is that since the content type is application / json, how does it matter bodyParser.urlencoded({ extended: true })

(or false)?

0


source to share


2 answers


The problem with form: JSON.stringify(class)

your first request. form

takes url encoded form input, stringified json won't work. check the content type header (application / x-www-form-urlencoded)



json: class

in the second snippet of work as this is handling the json data and setting the correct content type header correctly.

+1


source


Try the .toJSON () method in front of the class before submitting.



0


source







All Articles