【问题标题】:How to pass object in http.send() function?如何在 http.send() 函数中传递对象?
【发布时间】:2017-11-12 15:00:03
【问题描述】:

我正在尝试使用以下代码向 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})) 它对我有用。

【问题讨论】:

  • params 中的数据是什么?还要发布服务器端代码。您能否通过邮递员或休息客户端成功提出请求?如果是这样,则可能是上述代码的问题,否则可能是服务器端代码问题。
  • 您确定您的 params 对象是有效的 JSON 吗?你的代码对我有用。
  • @KrishnadasPC 这是一个完整的 json 对象,已传递给此函数。
  • @Mark_M 是的,Caleb 的解决方案对我有用。谢谢
  • 很高兴它成功了。当您发布包含完整数据的问题帖子时。您可以使用虚拟值,但发布完整信息总是有帮助的。

标签: javascript http post vue.js


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    【讨论】:

      【解决方案3】:

      您可以为此使用新的fetch 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
      });
      

      此外,如果您是新手,它会让事情更快地工作并帮助您更快地解决问题。

      【讨论】:

        猜你喜欢
        • 2023-04-05
        • 2012-06-13
        • 2017-04-05
        • 1970-01-01
        • 2012-10-20
        • 1970-01-01
        • 2014-03-05
        • 2020-05-24
        • 2014-10-24
        相关资源
        最近更新 更多