What is the process for passing an object in the http.send() method?

I'm currently working on sending a POST request to a specific URL using the code below. However, when passing an object to the http.send(params) function, it's resulting in a (400) bad request error. I'm having trouble pinpointing 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)

Fix: To resolve this issue, use http.send(JSON.stringify({'email': params.email, 'password': params.password})). This adjustment worked for me.

Answer №1

From what I can see, the problem lies in your attempt to transmit an entire object instead of using JSON. To rectify this situation, you should utilize

http.send(JSON.stringify(params))

Answer №3

Utilizing the latest fetch API makes the process much simpler and requires less code.

// Simply call the fetch function with the API's URL as a parameter
fetch(url) 
.then(function(response) {
    // Write your code to handle the data received from the API here
})
.catch(function() {
    // Implement code in case of server errors
});

If you are new to this, using the fetch API will accelerate getting things up and running, ultimately helping you resolve issues more efficiently.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble getting the redirect to work properly using $.ajax post in PHP

Can anyone help me figure out why my attempt to redirect using PHP on a $.ajax post is not working? Here is the jQuery AJAX code I am using: $("#customer_logout_link").click(function() { $.ajax({ type: "POST", data: { var: ...

Looking for tips on resolving issues with the bootstrap navigation bar?

Check out this code snippet: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport ...

Examining - Assessing the Link (next/link)

I am currently working on writing unit tests to verify the functionality of my navigation links. Here is a snippet from my MainNavigation.js file: import Link from 'next/link'; const MainNavigation = () => { return ( <header> ...

Tips for changing an input value when clicked using JQuery

Struggling to create an interactive mind mapping tool using JQuery? One challenge I'm facing is editing the content of a div once it's been set. I've implemented a function that successfully adds text to a div within the (mind-container). H ...

Tips on sorting an array of JSON objects using various integer requirements and specific key values

Having trouble implementing an interactive search filter in VueJS (Check out the CodePen for a dropdown and range app) I've managed to filter boat data by BrandName, BrandYear, Price... using selected = {...}, but I need help optimizing the if-statem ...

Choose Your Preferences When the Page Loads

I have a dropdown menu where I can select multiple options at once without checkboxes. When the page loads, I want all of the options to be pre-selected by default. I am aware that I can use $(document).ready() to trigger actions after the page has load ...

Converting a string to HTML in Angular 2 with proper formatting

I'm facing a challenge that I have no clue how to tackle. My goal is to create an object similar to this: { text: "hello {param1}", param1: { text:"world", class: "bla" } } The tricky part is that I want to ...

"Make your slides smooth and responsive with the unslick option in slick

Currently implementing the Slick Slider on a WordPress website. The slider is designed to display 3 columns at a screen size of 1024px and above. When the screen size drops below 1024px, the slider adjusts to show 2 columns, and on mobile devices, it swit ...

initiate scanning for HTTP GET calls

My current project involves using electron to create an application that serves multiple image files through a webserver using express. Another app built for Android is responsible for retrieving and posting files to this server. While I have successfully ...

Implementing a jQuery change event to filter a specific table is resulting in filtering every table displayed on the page

I have implemented a change event to filter a table on my webpage, but I am noticing that it is affecting every table on the page instead of just the intended one. Below is the code snippet: <script> $('#inputFilter').change(function() { ...

What is the best way to sort and organize JSON data?

Upon successful ajax call, I receive JSON data structured like this: var videolist = [ { "video_id": 0, "video_name": "Guerrero Beard", "timelength": 15 }, { "video_id": 1, "video_name": "Hallie Key", "timelength": 8 }, { ...

Evaluate the advancement of a test using a promise notification for $httpBackend

I am currently utilizing a file upload feature from https://github.com/danialfarid/angular-file-upload in my project. This library includes a progress method that is triggered when the xhr request receives the progress event. Here is an excerpt from the so ...

Best practice for setting up components in Angular 2 using HTML

I have developed a component that relies on external parameters to determine its properties: import { Component, Input } from '@angular/core'; import { NavController } from 'ionic-angular'; /* Info card for displaying informatio ...

Loop through a JSON object using a sequence of setTimeout() functions

After running another function, I have retrieved a JSON object stored in the variable 'json_result'. My objective is to log each individual JSON part (e.g. json_result[i]) after waiting for 5 seconds. Here was my initial attempt: for (let key ...

Enhance your HTML rendering with Vue.js directives

Check out this cool code example I created. It's a simple tabs system built using Vue.js. Every tab pulls its content from an array like this: var tabs = [ { title: "Pictures", content: "Pictures content" }, { title: "Music", c ...

Is the xmlhttprequest timeout/abort feature not functioning as anticipated?

Check out this snippet of my AJAX function: /** * This function initiates an AJAX request * * @param url The URL to call (located in the /ajax/ directory) * @param data The data to send (will be serialized with JSON) * @param callback The fu ...

Guide on downloading a PDF file with NodeJS and then transmitting it to the client

My goal is to download a PDF file using NodeJS and then send its data to the client to be embedded in the page. Below is the code snippet I am using to download the PDF file: exports.sendPdf = function(req, responce) { var donneRecu = req.body; va ...

Cypress - Mastering negative lookaheads in Regular Expressions

While experimenting with Cypress, I encountered an issue regarding a filter test. The goal is to verify that once the filter is removed, the search results should display values that were filtered out earlier. My attempt to achieve this scenario involves ...

Resolving the issue of nested modals within Bootstrap

I am experiencing some issues with my customer visits list page. When I try to add a visit, it opens a bootstrap popup ("#Pop1") to record the visit details. Within this modal, there is an option to add a new customer on the spot, which then triggers anoth ...

Capturing error responses in a successful Javascript HTTP GET request

When I make an http request to a url, it returns a 500 error response as expected. However, the error is being captured in the success function instead of the error function. $http.get("myUrl") .then(function (response) { console.log(response) ...