0

I'm developing an API, I want it to work with ajax request in client side. I also am using Nelmio Cors and FOS Rest.

AJAX GETs work fine. AJAX POST throws this error back to me (I'm testing with jQuery btw):

...
exception: [{message: "Invalid json message received",…}]
  0: {message: "Invalid json message received",…}
    class: "Symfony\Component\HttpKernel\Exception\BadRequestHttpException"
    message: "Invalid json message received"
...

My nelmio cors config is this:

nelmio_cors:
    defaults:
        allow_credentials: true
        allow_origin: []
        allow_headers: []
        allow_methods: []
        expose_headers: []
        max_age: 0
        hosts: []
        origin_regex: false
    paths:
       '^/api/':
           allow_origin: ['*']
           allow_headers: ['*']
           allow_methods: ['POST', 'PUT', 'GET', 'DELETE','OPTIONS']
           max_age: 3600

My request sends son data in the body and is this:

$.ajax({
  url:"http://127.0.0.1:8000/api/agents",
  type:"POST",
  data:{name: "asdf"},
  contentType:"application/json",
  dataType:"json",
  success: function(a){
    console.log(a);
  }
});

My web service is working fine if I perform this request over an http client.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
danielrvt
  • 10,177
  • 20
  • 80
  • 121
  • Looks like the data received is not in a correct json format, can you use Query.parseJSON('asdf'), if it doesn't help try to var dump the value of the sent data – Nawfal Serrar Mar 16 '15 at 07:24

1 Answers1

1

Your json in your request is not valid.

Replace

data:{name: "asdf"},

by

data:{"name": "asdf"},

Then

$.ajax({
    url:"http://127.0.0.1:8000/api/agents",
    type:"POST",
    **data:{"name": "asdf"},**
    contentType:"application/json",
    dataType:"json",
    success: function(a){
       console.log(a);
    }
});
AlexB
  • 7,302
  • 12
  • 56
  • 74