jpamorgan jpamorgan - 4 months ago 18
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 = {};
$, job, config).then(
function successCallback(response) {
$scope.loading = false;
}, function errorCallback(response) {
$scope.loading = false;

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

app.use(function (req, res, next) {
var domainWhitelist = [''];
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');
});'/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"}': '' }


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

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