2016-07-16 12 views
2

このフォーラムや他のサイトでこの質問に対する多くの回答を読んだことがありますが、コードは正常ですが問題は解決しません。 POSTリクエストをすると、400エラーコード(悪いリクエスト)が出ます。しかし、私はPOSTMANクライアントから同じリソースを呼び出すとき、私は正常に応答を取得します。誰も私のコードを見て、私が間違っているのを見てください。AjaxのPOST要求が機能しません

public class Country{ 

    int id; 
    String countryName; 

    @JsonCreator 
    public Country(@JsonProperty("id")int id, @JsonProperty("countryName")String countryName) { 
     this.id = id; 
     this.countryName = countryName; 
    } 
    ....setter/getters 
    } 

RESTコントローラーコードのこのビットは、私には間違って見える

$(function() { 
     var $ords = $('#orders'); 
     var $cid = $('#cid'); 
     var $name = $('#name'); 

     function displayOrder(country){ 
      $ords.append('<li>Id :' + country.id + ',name : '+ country.countryName + '</li>'); 
     } 
     $.ajax({ 
        type : 'GET', 
        url : 'http://localhost:8080/SpringRestfulWebServicesWithJSONExample/countries', 

        success : function(data) { 
         // data = JSON.parse(data); 
         $.each(data, function(i, country) { 
          displayOrder(country); 
         }); 
        }, 
        error : function() { 
         alert("error loading data"); 
        } 
       }); 
     $("#add").on("click", function(){ 
      var country= { 
        id:$cid.val(), 
        countryName:$name.val() 
      }; 
      $.ajax({ 
       type : 'POST', 
       url : 'http://localhost:8080/SpringRestfulWebServicesWithJSONExample/addCountry', 
       data:country, 
       contentType: "application/json", 
       success : function(newData) { 
        // data = JSON.parse(data); 
        $.each(newData, function(i, country) { 
         displayOrder(country); 
        }); 
       }, 
       error : function() { 
        alert("error loading data"); 
       } 
      }); 
     }); 
    }); 

@RestController 
    public class CountryController { 
     static List<Country> listOfCountries = new ArrayList<Country>(); 
     static{ 
      createCountryList(); 
     } 
     @RequestMapping(value = "/countries", method = RequestMethod.GET,headers="Accept=application/json") 
     public List<Country> getCountries() 
     { 
      return listOfCountries; 
     } 

     @RequestMapping(value = "/addCountry", method = RequestMethod.POST,headers="Accept=application/json") 
     public List<Country> addCountry(@RequestBody Country country) 
     {System.out.println("addcountry called"+country); 
      listOfCountries.add(country); 
      return listOfCountries; 
     } 

     @RequestMapping(value = "/country/{id}", method = RequestMethod.GET,headers="Accept=application/json") 
     public Country getCountryById(@PathVariable int id) 
     { 

      for (Country country: listOfCountries) { 
       if(country.getId()==id) 
        return country; 
      } 

      return null; 
     } 

    // Utiliy method to create country list. 
     public static List<Country> createCountryList() 
     { 
      Country indiaCountry=new Country(1, "India"); 
      Country chinaCountry=new Country(4, "China"); 
      Country nepalCountry=new Country(3, "Nepal"); 
      Country bhutanCountry=new Country(2, "Bhutan"); 

      listOfCountries.add(indiaCountry); 
      listOfCountries.add(chinaCountry); 
      listOfCountries.add(nepalCountry); 
      listOfCountries.add(bhutanCountry); 
      return listOfCountries; 
     } 
    } 

JSファイルの内容をファイルHTMLページの関連セクション

<body> 
    <h2>Country Names</h2> 
    <ul id="orders"> 
    </ul> 
    <p>Id: <input type="text" id="cid"></p> 
    <p>Name: <input type="text" id="name"></p> 
    <button id="add">Add</button> 
</body> 
+0

data:country, 

:contentTypeのを設定すると、自動的にあなたがあなた自身に

変更を、それをシリアル化するために必要なデータをJSONに変換しません。ブラウザのdevツールコンソールでCORSエラーが表示される – charlietfl

+0

いいえ、ページは8080で実行されていて、サービスコントローラも同じポートで実行されています。 – Surinder

+0

実際のリクエストをブラウザのdevツールネットワークで調べて、送信された内容を正確に確認してください – charlietfl

答えて

0

あなたはJSONを送信していません。ページが別のポート上にある場合は、サーバーでCORSを実装する必要が

data:JSON.stringify(country), 
+0

Wow、すばやくありがとうございました。 – Surinder

0

var country = { 
       id:$cid.val(), 
       countryName:$name.val() 
       }; 

私はそれをこのような何か書くでしょう:idcountryName周り

var id = $cid.val(), 
    countryName = $name.val(); 

var country = { 
    "id":id, 
    "countryName":countryName 
} 

二重引用符を使用すると、POSTリクエストで重要です。

+0

名前に特殊文字が使用されていない限り、引用符はオブジェクトキーでは重要ではありません。最初に値の変数を作成しても影響はありません。オブジェクト自体が送信される前にシリアル化されます – charlietfl

+0

返信ありがとうございます。このコードはcodeAcademyチュートリアルのものです。とにかく、私はあなたの提案を変更しましたが、それでも同じエラーが表示されます。 リソースを読み込めませんでした:サーバーがステータス400で応答しました(Bad Request。 – Surinder

関連する問題