0

I'm trying to send data to my NodeJS server with express.

The problem is that when I'm making the http post, the data gets wrapped in an object, where the data is the key in this object, and the value gets empty.

http({
    method: 'POST',
    url: '/api/booking', 
    data: {test:"data"},
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
    }
    }).then(function successCallback(response) {
        console.log(response)
    }, function errorCallback(response) {
        console.log("API request failed: "+response);
    });

the response will be like this;

{ '{"test":"data"}': '' }

I've tried a ton of different solutions which i have searched for. But I can't figure what the problem is.

I've also tried using postman, and in that case it works just fine.

Thanks!!

Problem not solved, but bypassed;

JSON.parse(Object.keys(req.body)[0]);

on serverside.

Wipesh
  • 1
  • 1

3 Answers3

0

Have you try {'test':'data'} ?

GG.
  • 21,083
  • 14
  • 84
  • 130
qchap
  • 345
  • 6
  • 17
  • Have you try your API with an other tool like postman ? The result it's the same ? – qchap Apr 16 '16 at 21:28
  • Yes... and the object is correct when i send it with postman, which is even more disturbing. – Wipesh Apr 19 '16 at 14:16
  • have you put `$http` in your code ? Or just http like on your post ? – qchap Apr 19 '16 at 14:50
  • Yeah. I'm just doing like this: ['$scope','$http','$cookies', function(scope,http,cookies){ – Wipesh Apr 19 '16 at 18:21
  • I doesn't see anything on this little piece of code ... I try to reproduce your syntaxe on my side but all is ok. Can you post the complete example on plunker ? – qchap Apr 19 '16 at 18:36
  • First time on Plunker, not sure if you get the idea. But this is more or less the whole concept.. i think. https://plnkr.co/edit/viTRvMfbW1mfHFlk3nkz?p=preview – Wipesh Apr 19 '16 at 19:15
  • I never use paramSerializer but it doesn't seem efficient on POST Body. http://stackoverflow.com/questions/32320267/why-angular-still-encode-request-as-json-http-httpparamserializerjqlike – qchap Apr 19 '16 at 19:40
0

have you tried to encode or stringify the data?

window.encodeURIComponent( {test:"data"} )

or

JSON.stringify( {test:"data"} )
4UmNinja
  • 510
  • 4
  • 14
  • None works.. thank you very much though. I've tried to change the version of angular that I'm using in case of bugs. But it didnt change anything. – Wipesh Apr 19 '16 at 14:17
0

you just need to add the following code to your server file, this will parse the incoming json requests for you

app.use(bodyParser.json());