2016-11-21 24 views
0

編輯:這可能與後端API的問題嗎?通過$ .param發送的數據請求總是字符串,是正確的?所以他們需要在後端解析這些東西?設置角度HTTP數據變量之一的布爾

目前我正在試圖發送POST請求API來註冊用戶。其中一項要求是接受的條款和條件和年齡要求,它需要一個布爾值。

我相信這個問題可能是,$ HTTP請求發送一個字符串,而不是一個boolean值以API後端,因此它拒絕它。我將如何通過$ http發送布爾值?

var apiCall = { 
     method: 'POST', 
     url: 'API_URL', 
     data: $.param({ 
     'user[email]': username, 
     'user[password]': password, 
     'user[password_confirmation]':password, 
     'profile[age_acceptance]': ageAcceptance, 
     'profile[terms_acceptance]': termsAcceptance 
     }), 
     headers: { 
     'Accept': 'application/vnd.softswiss.v1+json', 
     'Content-Type': 'application/x-www-form-urlencoded' 
     }, 
     transformRequest: function(data, headersGetter, status) { 
     console.log(data); 
     console.log(headersGetter(data)); 
     } 
    } 
+0

嘗試使用的console.log語句(或開發工具調試器),看看有什麼'typeof運算termsAcceptance'回報。然後你會確定它是否是類型問題。 – timothym

+0

已經完成。傳遞到$ .param的值是布爾值 - 但是當我記錄轉換請求時,它只是一個大字符串(這可能是正常的,但我只是想弄清楚爲什麼我會被API拒絕)。 – Tulun

+0

貴API接受' '的Content-Type':「應用程序/ json'',而不是'的X WWW的形式urlencoded'? – georgeawg

回答

0
var dataToPost = JSON.stringify({ 
    'user[email]': username, 
    'user[password]': password, 
    'user[password_confirmation]':password, 
    'profile[age_acceptance]': ageAcceptance, 
    'profile[terms_acceptance]': termsAcceptance 
    }); 

    data: dataToPost, 
    headers: {......., 
    ..... 

你有你的弦參數。

JSON.stringify(params) 
+0

修改API調用是這樣的: 錯誤消息說,現在電子郵件地址無效。不知道這是正確的解決方案。 data:$ .param('user [email]':JSON.stringify(username), 'user [password]':JSON.stringify(password), 'user [password_confirmation]':JSON.stringify密碼), 'profile [age_acceptance]':JSON.stringify(ageAcceptance), 'profile [terms_acceptance]':JSON.stringify(termsAcceptance) }), – Tulun

+0

修改了我的答案。希望這項工作爲你, –

+0

所以,api期待這樣的迴應: 「user%5Bemail%5D = a%40b.x&user%5Bpassword%5D = test1234&user%5Bpassword_confirmation%5D = test1234&profile%5Bage_acceptance%5D = true&profile% 5「=」5「=」0「=」0「=」0「=」0「=」0「=」0「=」0「=」用戶[password_confirmation] 「:」 test1234" , 「個人資料[age_acceptance]」:真正的 「個人資料[terms_acceptance]」:真正}」 我認爲,因爲API期待一個大的字符串,我不能使用JSON.stringify。 .. 但如果它想要一個布爾值,我不確定$。參數發送除字符串以外的任何內容。嗯。 – Tulun