簡體   English   中英

Symfony2 FosRestBundle 和 NelmioCorsBundle 的 Ajax 發布請求

[英]Ajax post request with Symfony2 FosRestBundle and NelmioCorsBundle

我正在開發一個 API,我希望它在客戶端處理 ajax 請求。 我也在使用 Nelmio Cors 和 FOS Rest。

AJAX GET 工作正常。 AJAX POST 將此錯誤返回給我(順便說一句,我正在使用 jQuery 進行測試):

...
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 無效。

代替

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM