1

I would like post object and read it on node server but I have an error.

controller :

$scope.update = function(contact) {
console.log(contact);
    $http.post('/contactlist/' + contact).then(function(response) {
        console.log(response);

    });
};

server node :

app.post('/contactlist/:contact', function (req, res, next) {
    console.log(req.body);
    res.json();
});

server node head:

var express =  require('express');
var app = express();
var mysql      = require('mysql');
var bodyParser = require('body-parser');
var connection = *****************

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({extended:false}));
app.use(express.static(__dirname + "/public"));

Screenshot of the error network POST : enter image description here

server error of console.log(req.body);

[object Object] SyntaxError: Unexpected token o in JSON at position 1

2 Answers 2

1

You are not passing any parameter in your post API. POST needs a parameter to be passed and since you are passing the parameter in the request URL, you can try by passing an empty object like this:

 $http.post('/contactlist/' + contact,{}).then(function(response) {
        console.log(response);

    });

You are trying to concatenate an object in the URL which is not a good approach. If you want to still do this way, stringify it and then append it to URL. And you can get it with the help of req.query. But it is better if you change the url and pass contact as a parameter to your API call.

Problem solved by :

var OBJ = JSON.stringify(yourOBJ);
Sign up to request clarification or add additional context in comments.

7 Comments

I think you are passing an array contact
You need to stringify the array before
How do you know if it's an array? chrome say: Object {id: 571, name: "QSDF", email: "QSDFQSD", number: "FQSDF"} it's not JSON?
It is a JSON only and not an array but you have to handle it correctly. If it is an object, why don't you pass it as $http.post('/contactlist/' , contact).then(function(response) { console.log(response); }); And change your nodejs code
I stringified but I have another problem cause I have 2 post into differrent scope. $scope.add $scope.update Node server results the first one of server.js ( post from add ). Do you know how to solve this?
|
1

For node js there different syntax please see below:

var yourObj = {}; 
$http.post('/contactlist/' + contact, {data: yourObj}).then(function(response) 
{
    console.log(response);

});

This will work

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.