Taha Taha - 3 months ago 10
JSON Question

How to pass a json object to node js server

I want to create a hybrid mobile application where the backend is Node js that it will save data in mongodb my server works properly I prepared routes for handling users requests

I can get data from my server using GET method but my problem that I can't save data that is sended from ionic user interface using POST method. I tried to send data using POSTMAN the data was saved succesfully in mongodb but the problem occur when I send data from mobile user interface

this is a picture to show the results in node js server of sending POST request using POSTMAN
and sending POST request from mobile user interce

enter image description here

and this how data is saved in mongoDB

enter image description here

this is my routes file in node server

var Product = require('../models/product');
var express = require('express');
var router = express.Router();

router.route('/products')


.get(function(req, res) {


Product.find(function(err, products) {
if (err) {
return res.send(err);
}

res.json(products);
});


})

.post(function(req, res) {


console.log(req.body);

var product = new Product(req.body);


product.save(function(err) {
if (err) {
return res.send(err);
}

res.send({ message: 'product Added' });
});
});


this is the form

<label class="item item-input">

<input name="1" type="text" ng-model="product.nom" placeholder="nom du produit">
</label>

<label class="item item-input" >

<input name="2" type="text" ng-model="product.unite" placeholder="unité de cette produit">
</label>

...


<div class="item button button-block button-positive" ng-click="createProduct(product)" >
ajouter le produit
</div>


and this is the controller of products :

app.controller('productController', function($http, $scope) {



$scope.createProduct = function (new_prod){

console.log(new_prod);

var req = {
method: 'POST',
url: "http://localhost:3000/api/products",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},

data: new_prod
};

$http(req)
.then(function(response) {
console.log(response);


});

};

Answer

If you're posting JSON you shouldn't be using a content-type of application/x-www-form-urlencoded. Use application/json instead.

https://tools.ietf.org/html/rfc4627

application/x-www-form-urlencoded isn't for json, it's for data like you see in urls:

key=value&foo=bar
Comments