Varkal
Varkal

Reputation: 1388

Post JSON data from AngularJS Client to Express Server

I try to post a JSON Object with AngularJS $http service to an Express Server. But I get an empty object in the server : "{}"

I see this topic but this not solve my issue : angular post json to express

Here code of Angular client :

self.postTicket = function(ticket){
        $http({
            url: baseUrl+"features/",
            method: "POST",
            body: ticket,
            headers: {'Content-Type': 'application/json'}})
}

I check the "ticket" object and it isn't empty

And here, the express server :

var express = require("express");
var request = require("request");
var bodyParser = require('body-parser')


var app = express();

app.use(bodyParser.json({}));

app.post('*', function (req, res) {
    console.log(req.body);
    res.status(200).send('OK');
});


app.listen(9000);

Thank you in advance for your help

Upvotes: 3

Views: 3635

Answers (2)

Francis Ezengige
Francis Ezengige

Reputation: 108

Replace

self.postTicket = function(ticket){
    $http({
        url: baseUrl+"features/",
        method: "POST",
        body: ticket,
        headers: {'Content-Type': 'application/json'}})

with

self.postTicket = function(ticket){
    $http({
        url: baseUrl+"features/",
        method: "POST",
        data: ticket,
        headers: {'Content-Type': 'application/json'}})

Upvotes: 0

Artem Petrosian
Artem Petrosian

Reputation: 2954

Use data property instead of body in your $http call

$http({
            url: baseUrl+"features/",
            method: "POST",
            data: ticket,
            headers: {'Content-Type': 'application/json'}})

Upvotes: 1

Related Questions