0

I am trying to make a post request to a url with the following code . Passing object to http.send(params) function gives (400) bad request error. 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 .

5
  • 1
    What is the data in params? Also post the server side code. Are you able to make the request successfully with postman or rest client? If so it might be the problem with the above code otherwise it might be server side code issue. Commented Nov 12, 2017 at 6:04
  • 1
    Are you sure your params object is valid JSON? Your code works for me. Commented Nov 12, 2017 at 6:04
  • @KrishnadasPC it was a json complete object which was passed to this function. Commented Nov 12, 2017 at 6:56
  • @Mark_M yes it is , Caleb's solution worked for me . Thanks Commented Nov 12, 2017 at 6:57
  • Glad it worked. When you post a question post with full data. You can use dummy values but posting with complete information always helps. Commented Nov 12, 2017 at 7:23

3 Answers 3

1

It seems to me that your issue is that you are trying to send a whole object instead of JSON. The correct way to do this would be to use http.send(JSON.stringify(params))

Sign up to request clarification or add additional context in comments.

Comments

1

You should use one of three ways to do it https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#A_brief_introduction_to_the_submit_methods

Or either, you can take Axios.

Comments

1

You can use the new fetch API for this, makes it dead easy and less code

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.