jpamorgan jpamorgan - 1 month ago 6
JSON Question

Angularjs JSON POST data received as key instead of value in Express.js

I am trying to send a POST request with JSON data from angularjs to node/express, but all the data is showing up in the KEY of the req.body instead of key value pairs.

I saw this question with the same issue, but the solution did not fix my problem: Express.js : POST data as KEY of a req.body object instead of VALUE of req.body

Here is my client side code (ANGULARJS):

var job = {
session_id: $scope.uid,
timestamp: 0,
invoice_id: $params.i
};
var url = 'https://example/' + $scope.uid;

var config = {
headers : {
'Content-Type' : 'application/json; charset=UTF-8'
}
};

//var config = {};
$http.post(url, job, config).then(
function successCallback(response) {
$scope.loading = false;
console.log('Success:', response.data)
}, function errorCallback(response) {
$scope.loading = false;
console.log('Error:', response.data)
});


Here is my server side code (NODEJS/EXPRESS):

app.use(bodyParser.json());
app.use(function (req, res, next) {
var domainWhitelist = ['https://www.example.com'];
var origin = req.headers.origin;
if(domainWhitelist.indexOf(origin) > -1){
res.setHeader('Access-Control-Allow-Origin', origin);
}
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
next();
});
app.post('/payment/:session', function(req, res) {
var data = req.body;
console.log('data:', data)
});


This is the data I get on the server side:

{'{"session_id":"123","timestamp":0,"invoice_id":"-test"}': '' }

Answer

I was able to fix this problem on my own using the answer in this question:

http://stackoverflow.com/a/18311469/975669

I had to set the header: 'Access-Control-Allow-Headers' in express:

res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

The whole thing looks like this:

// Add headers
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});
Comments