[英]http.send returns [object object] at the backend (Node + Express)
[英]How to pass object in http.send() function?
我正在嘗試使用以下代碼向URL發出發布請求。 將對象傳遞給http.send(params)函數會產生(400)錯誤的請求錯誤。 我無法在這里找到問題所在。
var http = new XMLHttpRequest()
var url = 'http://somerandomurl'
http.open('POST', url, true)
http.setRequestHeader('content-type', 'application/json')
http.setRequestHeader('accept', 'application/json')
http.onreadystatechange = function () {
if (http.readyState === 4 && http.status === 200) {
returndata = http.responseText
console.log(JSON.parse(returndata))
}
}
http.send(params)
解決方案:http.send(JSON.stringify({'email':params.email,'password':params.password}))對我有用。
您應該使用以下三種方式之一進行操作:https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#A_brief_introduction_to_the_submit_methods
您也可以選擇采用Axios。
您可以為此使用新的訪存API ,從而使其變得非常簡單且代碼更少
// Call the fetch function passing the url of the API as a parameter
fetch(url)
.then(function(response) {
// Your code for handling the data you get from the API
})
.catch(function() {
// This is where you run code if the server returns any errors
});
另外,如果您是新手,它將使工作更快,並幫助您更快地解決問題。
在我看來,您的問題是您正在嘗試發送整個對象而不是JSON。 正確的方法是使用http.send(JSON.stringify(params))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.