Ajax 打到controller,返回 400


Posted by c9103205 on 2021-07-26

今日在前端頁面撰寫一個ajax
打到後端的測試接口
前端代碼如下

function queryGroupName() {
    var jsonEx = { "inputText": "test" };
    $.ajax({
        url: '/ADG02005/queryGroup',
        contentType: "application/json",
        method: 'post',
        data:jsonEx,
        dataType: 'json',

        contentType: "application/json; charset=utf-8",
        beforeSend: function () {

        },
        success: function (res) {
            console.log(res)

        },
        error: function (err) {
            alert('系統錯誤!')
            console.log(err.responseText);
        },
    });
}

系統返回錯誤,html 狀態碼 400
bad request
通常4XX 系列,依我經驗,都會先去懷疑接口有沒有問題
於是用postMan測試

確定postMan是有撈到資料
解決方法:

  data:jsonEx,
   加上 JSON.stringify 
   更正成 data:JSON.stringify(jsonEx),

因為contentType已經指定傳入的格式為 json,所以必須格式化輸入的格式為Json,否則後端無法接受


#javascript #JSON







Related Posts

Beaglebone Black 刷新 EMMC 筆記

Beaglebone Black 刷新 EMMC 筆記

Git 狀況劇_我把錯的資料夾初始化了

Git 狀況劇_我把錯的資料夾初始化了

[Day03] Lazy Evaluation

[Day03] Lazy Evaluation


Comments