简体   繁体   English

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

[英]How to pass object in http.send() function?

I am trying to make a post request to a url with the following code . 我正在尝试使用以下代码向URL发出发布请求。 Passing object to http.send(params) function gives (400) bad request error. 将对象传递给http.send(params)函数会产生(400)错误的请求错误。 I am not able to trace the issue here . 我无法在这里找到问题所在。

     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)

Solution: http.send(JSON.stringify({'email': params.email, 'password': params.password})) it worked for me . 解决方案:http.send(JSON.stringify({'email':params.email,'password':params.password}))对我有用。

You can use the new fetch API for this, makes it dead easy and less code 您可以为此使用新的访存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
});

Also if your a newbie it will get things working quicker and help you solve your problem faster. 另外,如果您是新手,它将使工作更快,并帮助您更快地解决问题。

It seems to me that your issue is that you are trying to send a whole object instead of JSON. 在我看来,您的问题是您正在尝试发送整个对象而不是JSON。 The correct way to do this would be to use http.send(JSON.stringify(params)) 正确的方法是使用http.send(JSON.stringify(params))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM