Javascript 如何在http.send()函数中传递对象?

Javascript 如何在http.send()函数中传递对象?,javascript,http,post,vue.js,Javascript,Http,Post,Vue.js,我正在尝试使用以下代码向url发出post请求。 将对象传递给http.send(params)函数会产生(400)错误请求错误。 我无法在这里追踪这个问题 var http = new XMLHttpRequest() var url = 'http://somerandomurl' http.open('POST', url, true) http.setRequestHeader('content-type', 'application/jso

我正在尝试使用以下代码向url发出post请求。 将对象传递给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}))对我有效。

您应该使用以下三种方法之一


或者,您可以使用Axios。

您应该使用以下三种方法之一

或者,你也可以使用Axios。

你可以使用新的,使它非常简单,代码更少

// 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
});
此外,如果你是一个新手,它会让你的工作更快,并帮助你更快地解决你的问题

您可以使用新的,使它非常简单,代码更少

// 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))

在我看来,您的问题是试图发送整个对象而不是JSON。正确的方法是使用http.send(JSON.stringify(params))

params中的数据是什么?同时发布服务器端代码。您是否能够使用postman或rest客户端成功地发出请求?如果是这样,则可能是上述代码有问题,否则可能是服务器端代码问题。是否确定
params
对象是有效的JSON?你的代码对我有用。@KrishnadasPC它是一个json完整对象,被传递给这个函数。@Mark\M是的,Caleb的解决方案对我有用。谢天谢地,成功了。当你发布一个包含完整数据的问题帖子时。您可以使用虚拟值,但发布完整信息总是有帮助的。参数中的数据是什么?同时发布服务器端代码。您是否能够使用postman或rest客户端成功地发出请求?如果是这样,则可能是上述代码有问题,否则可能是服务器端代码问题。是否确定
params
对象是有效的JSON?你的代码对我有用。@KrishnadasPC它是一个json完整对象,被传递给这个函数。@Mark\M是的,Caleb的解决方案对我有用。谢天谢地,成功了。当你发布一个包含完整数据的问题帖子时。您可以使用虚拟值,但发布完整信息总是有帮助的。