[英]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.