anand tiwari
anand tiwari

Reputation: 21

Trying to post json in angularjs will 400 bad request

I am trying to post a static new entry using angularjs $http call but it will throws 400 bad request I am not getting why? Here I am passing the exact same type of json object in input.

Below is my main json file in which I want to add new record .

{
    "count": 384,
    "next": "http://104.197.128.152:8000/v1/tracks?page=2",
    "previous": null,
    "results": [
        {
            "id": 38,
            "title": "Hey Jude",
            "rating": "4.9",
            "genres": [
                {
                    "id": 5,
                    "name": "ramesh"
                }
            ]
        },
        {
            "id": 39,
            "title": "hello adele",
            "rating": "4.0",
            "genres": [
                {
                    "id": 4,
                    "name": "bollywood"
                },
                {
                    "id": 8,
                    "name": "metakai"
                }
            ]
        }
    ]
}

Data which I want to post:

var data = {
    "id": 79,
    "title": "new song anand",
    "rating": "4.0",
    "genres": [
        {
            "id": 4,
            "name": "bollywood"
        },
        {
            "id": 8,
            "name": "metakai"
        }
    ]
}

Syntax for posting data:

$http({
          method: 'POST',
          url: 'http://104.197.128.152:8000/v1/tracks',
          dataType: 'json',
          data: data,
          headers: { 'Content-Type': 'application/json; charset=UTF-8' }
          }).success(function (data) {
            console.log(data,"success");
          }).error(function (data) {
            console.log(data,"fail");
          });

Upvotes: 1

Views: 249

Answers (1)

WhoAmI
WhoAmI

Reputation: 317

Remove dataType: 'json' and charset=UTF-8 from headers.

$http({ method: 'POST', url: 'http://104.197.128.152:8000/v1/tracks', data: data, headers: { 'Content-Type': 'application/json'} }).success(function (data) { console.log(data,"success"); }).error(function (data) { console.log(data,"fail"); });

It must work .

And if not re-check your JSON format. Something must be missing.

Upvotes: 1

Related Questions