带有Symfony2 FosRestBundle和NelmioCorsBundle的Ajax发布请求

问题描述 投票:0回答:1

我正在开发一个API,我希望它能与客户端的ajax请求一起使用。我也在使用Nelmio Cors和FOS Rest。

AJAX GET工作正常。 AJAX POST向我抛出此错误(我正在用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"
...

我的nelmio cors配置是这个:

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

我的请求在体内发送儿子数据,并且是这样:

$.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);
  }
});

如果我通过http客户端执行此请求,我的Web服务将正常工作。

json ajax symfony fosrestbundle
1个回答
1
投票

您的请求中的json无效。

替换

data:{name: "asdf"},

作者

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

然后

$.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);
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.