body-parser is not parsing json data - javascript

This is how I am using the package:
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
This is the body of my request:
{
name: "jay",
price: "12"
}
This is how I am extracting the body:
const name = req.body.name;
const price = req.body.price;
But both name and price returned undefined.
EDITED:
According to VS Code, this package is deprecated. But it should still work, no?

the request body should be JSON so property names should be in quote signs
{
"name": "jay",
"price": "12"
}

Related

mongoose Model.save() only returns { _id, __v }

I know this question has been asked before but I feel like I'm doing everything right and I'm still having an issue. I want to save an item from a form into my mongodb collection using mongoose.
My schema:
// stationmodel.js
export const StationSchema = new mongoose.Schema({
"FDID": String,
"Fire dept name": String,
"HQ addr1": String,
"HQ city": String,
"HQ state": String,
"HQ zip": Number,
"HQ phone": String,
"Dept Type": String,
"Organization Type": String,
"Website": String,
"Number Of Stations": Number,
"Primary agency for emergency mgmt": Boolean,
}, {collection: "FEMA_stations"})
In my express app:
// in routes.js
const StationSchema = require('./stationmodel')
const Station = mongoose.model('Station', StationSchema, 'FEMA_stations')
const addstation = (req, res) => {
console.log(req.body)
const newStation = new Station(req.body)
newStation.save( function(err){
if (err) { console.error(err) }
console.log('newStation after save', newStation)
})
}
const routes = app => {
app.route('/api/addstation')
.post(addstation)
}
export default routes
// in index.js
import routes from './routes'
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
routes(app)
In my front end code, calling to the backend in a redux action:
fetch('/api/addstation', {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(stationToAdd)
})
When I console.log(req.body) on my back end, I get the data I'm expecting. It looks something like this:
{
FDID: '202020',
'Fire dept name': 'Some Fire Department',
'HQ addr1': 'Some address',
'HQ city': 'San Dimas',
'HQ state': 'CA',
'HQ zip': 99999,
'HQ phone': '5555555555',
'Dept Type': 'Career',
'Organization Type': 'State',
Website: '',
'Number Of Stations': 0,
'Primary agency for emergency mgmt': true,
}
But when I console.log my newStation that I'm trying to .save(), all I get is a response like this:
{ _id: 5efe29911ea067248f3c39a0, __v: 0 }
I know other people had issues with their schema, their model, making sure that they're truly connected to their mongodb collection, or making sure that the request is made with the application/json header, but I feel I have all those things right. The code was pieced together from a much more modularized app to try to cut the fat and present the core issue, so let me know if I'm missing any glaring information.
What might be going wrong here? Why is the data from req.body not making it into my new document that I'm trying to save to the collection? Thanks for reading.
You are mixing es6 module import/export with Node.js CommonJS require.
In stationmodel.js You are using a "named export"
export const StationSchema = new mongoose.Schema(...
But in routes.js you are using CommonJS require
const StationSchema = require('./stationmodel')
Which is likely to be an empty object. So the following line will create a model with an "empty" schema
const Station = mongoose.model('Station', StationSchema, 'FEMA_stations')
The solution
use named import instead
import { StationSchema } from './stationmodel'
TIP:
Since you are already name the file stationmodel.js, which suggests it's a model. You can put the following in stationmodel.js directly to prevent the model from getting incorrect schema
export const Station = mongoose.model('Station', StationSchema, 'FEMA_stations')

When post to express server after use JSON.stringify, it doesn't work

I am trying to send a simple array to express server as JSON, then convert it back to an object on the server side.
Client side :
var hand = { cards: [] }
// I randomly generate some numbers and suits and then add to the array.
var card_obj = { "number": number, "suit": suit };
hand.cards.push(card_obj)
//Send to Express server
var hand_json = JSON.stringify(hand)
$.post("hand", hand_json, function(result) {
console.log(result);
});
Server side :
app.post("/hand", function(req, res) {
var cards = req.body.cards
console.log(cards[0])
});
This code is not working,as I receive on the server side console : Cannot read property '0' of undefined
BUT, it will work, If i changed the client code to the following :
var test = { "cards": [{ "number": "9", "suit": "club" }, { "number": "10", "suit": "club" }, { "number": "K", "suit": "spades" }, { "number": "A", "suit": "hearts" }, { "number": "5", "suit": "diamonds" }] }
$.post("hand", test , function(result) {
console.log(result);
});
The weird thing that the test variable is the same variable generated by JSON.stringify(hand), I just copied it form the console.
I don't understand why when use JSON.stringify(hand), it doesn't work. But when copy paste the object and then pass it, it works.
In order to send a post request content JSON in the body you need to make sure two things:
Since you are using JQuery. From client, you must use ajax function to include a contentType:"application/json in your request to inform the server you are sending a JSON file:
$.ajax({
url: url,
type:"POST",
data: JSON.stringify(hand),
contentType:"application/json",
dataType:"json",
success: function(result){
`...Do something when the data returned`
}
})
Now in the server, you should install and define a middleware to work as body parser for your post requests
Install npm install body-parser --save
And use it in express
const bodyParser = require('body-parser');
// support parsing of application/json type post data
app.use(bodyParser.json());
//And make sure your route is placed below the parser
app.post("/hand", function(req, res) {
var cards = req.body.cards
console.log(cards[0])
});

How to store parsed JSON value into a variable in Express?

I am using the body-parser to parse incoming JSON object in a POST message. I would like to store a particular value from the JSON into a variable to be sent to a database later.
Here is a snippet:
var http = require('http');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// Required to process the HTTP body.
// req.body has the Object while req.rawBody has the JSON string.
app.use(bodyParser.json()); // for parsing application/json
app.post('/', function(req, res){
var tropo = new TropoWebAPI();
parameters = req.body['session']['parameters'];
callerID = req.body['session']['from']['id'];
console.log(callerID);
if(callerID = 1234567)
{
\\Intentionally kept out
}
However, it fails with this TypeError: Cannot read property 'id' of undefined
#malix This is what the JSON object is:
"session": {
"id": "89c3b5d830dd8bb8b372f802aadbdfc9",
"accountId": "1234567",
"applicationId": "1234567",
"timestamp": "2016-06-23T17:09:48.685Z",
"userType": "HUMAN",
"initialText": null,
"callId": "7ab0b9306af2139a1a2e6cc8b7bd7af9",
"to": {
"id": "408XXXYYYY",
"name": "408XXXYYYY",
"channel": "VOICE",
"network": "SIP"
},
"from": {
"id": "408ZZZAAAA",
"name": "408ZZZAAAA",
"channel": "VOICE",
"network": "SIP"
},
}
I am trying to extract 408ZZZAAAA
Please assist.
I figured this out. Turns out the first POST message does give me the required result. The error only shows because my APP is configured to trigger a second POST from the source client. This second POST which triggers the same app.post(), does not have the "from" object all together. Therefore the error shows up on the second try, but I get what I need in the first post itself.

Insert embedded documents Mongo DB from express app

I have a mongo db schema like so
users:
{username:"",
age: "",
data: [
{field1:"", field2:""},
{field1:"", field2:""}
]
}
My problem is how do send over my user object to my express route to post data to the db.
Typically i create my user object like so:
var user= {username:"test" age: 20};
and send this user object with my ajax call to my adduser route.
Ho do i structure my above assignment to include my embedded documents.
when i use this structure:
sign_in_data: [{date:"",time_in:"",time_out:""}]
my database looks like this:
sign_in_data[0][date]: "",
sign_in_data[0][time_in]: "",
sign_in_data[0][time_out]: ""
but it should look like this:
sign_in_data: [
{
date: "2015-06-08",
time_in: "17:35",
time_out: "17:35"
},
]
at the moment when you are configuring express, review if you are using this line of code:
In case you are using Express 4.x version
Note: you need to have body-parser installed.
app.use(bodyParser.urlencoded({ extended: true }));
In case you are using Express 3.x version
app.use(express.urlencoded());
I did a test example where the property cars is an an array of objects send from the html file, and it is saving as you want in the database.
So this is my express server file:
// ..
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/api/user', function (req, res) {
var user = {
username: req.body.username,
age: req.body.age,
cars: req.body.cars
};
db
.collection('user')
.insert(user, function (err, result) {
if (err) return res.status(500).send(err);
res.send(result);
});
});
// ..
database data inserted:
{
"_id" : ObjectId("5578b48f1e8cdf0520bdf76f"),
"username" : "wilsonbalderrama",
"age" : "29",
"cars" : [
{
"name" : "Ferrari",
"color" : "Red"
},
{
"name" : "Mustang",
"color" : "Gray"
}
]
}
and my html file where I am sending the data, you can review it in this gist file:
https://gist.github.com/wilsonbalderrama/62f76a348c0aa217cdd9
Hope this helps you.

How to manipulate data returned from mongo db using mongoose

I've created a local database using mongo (using this tutorial actually)
It has a db named 'simple' and collection named 'people'. Then I import json with each element as
{
"id": 1,
"guid": "1581cfde-f2fc-44f8-8953-511331e943ab",
"isActive": true,
"firstName": "Ilene",
"lastName": "Kent",
"email": "carolegoodman#intrawear.com"
}
I then create the schema and Person model in my node app
var express = require('express');
var path = require('path');
var mongoose = require('mongoose');
var app = express();
app.set('port', (process.env.PORT || 5000));
mongoose.connect('mongodb://localhost/simple')
var personSchema = {
firstname: String,
lastname: String,
email: String
}
var Person = mongoose.model('Person', personSchema, 'people')
app.get('/users', function(req,res){
Person.find(function(err, doc){
var x = doc[0]
console.log(x)
console.log(Object.keys(x))
res.send(200);
});
});
On calling find() on the Person model I get logged (for console.log(doc[0])) - the first item in the doc returned:
{ _id: 548e41afa0bad91d53f34cce,
id: 0,
guid: 'af6a931d-1801-4662-9d52-c95dc97bac22',
isActive: false,
firstName: 'Janna',
lastName: 'Shelton',
email: 'crossoconnor#geekology.com' }
But my problem is that when I look for the property firstName on doc[0] (i.e. doc[0].firstName) I get an undefined.
I've tried diagnosing this and Object.keys(doc[0]) gives me:
[ '$__',
'isNew',
'errors',
'_maxListeners',
'_doc',
'_pres',
'_posts',
'save',
'_events' ]
meaning I suspect there must be some special methods for mongoose when you want to access the data from your returned elements - but I can't find the answer in documentation or here.
Thanks
You receive an array of Documents. Mongoose API
doc[0].get('firstName')
When you just want a plain JavaScript representation of the documents that you can freely manipulate, add lean() to your Mongoose query chain:
app.get('/users', function(req,res){
Person.find().lean().exec(function(err, docs){
var x = docs[0]
console.log(x)
console.log(Object.keys(x))
res.send(200);
});
});
Use .lean() in your query as below.
db.collection.find().lean().then(function(data){})

Categories