A comprehensive guide on using ajax to reproduce a Postman POST API request

Currently, I am able to retrieve an "access_token" using Postman; however, I am attempting to recreate this process in ajax for experimentation purposes on jsfiddle.

In Postman, the following setup is used:

  • A POST request URL:
  • No active headers
  • Body includes four key-value pairs (refer below)

https://i.sstatic.net/F8vJs.png

Executing the request results in a response containing the access_token:

https://i.sstatic.net/BfH5y.png

For replicating this in ajax, with assistance from others, the following script was created:

$.ajax({
  type: 'POST',
  url: 'https://login.microsoftonline.com/***/oauth2/token',
  data: JSON.stringify({
    grant_type: 'client_credentials',
    client_id: '***',
    client_secret: '***',
    resource: 'https://analysis.windows.net/powerbi/api'
  }),
  success: data => {
    console.log(data.access_token)
  },
  error: (xhr, textStatus, error) => {
    console.log('rr', error)
  }
});

However, every time this script is run, it returns an error in the console:

https://i.sstatic.net/IiJoi.png

Although I believe I am close to resolving the issue, I have not been able to figure it out yet.

Answer №1

Your POST request is in x-www-form-urlencoded format, but the data sent via ajax is in a json string.

When passing data as a string, it should already be encoded using the appropriate encoding for the contentType, which defaults to

application/x-www-form-urlencoded
.

With object data, jQuery automatically generates the data string from the key/value pairs unless the processData option is disabled. For instance, { a: "bc", d: "e,f" } is converted to the string "a=bc&d=e%2Cf". If a value is an array, jQuery serializes multiple values with the same key based on the traditional setting (explained below). For example, { a: [1,2] } becomes the string "a%5B%5D=1&a%5B%5D=2" with traditional set to false by default.

https://api.jquery.com/jquery.ajax/

Therefore, you can try omitting the use of JSON.stringify and directly pass the POJO. For example:

$.ajax({
  type: 'POST',
  url: 'https://login.microsoftonline.com/***/oauth2/token',
  data: {
    grant_type: 'client_credentials',
    client_id: '***',
    client_secret: '***',
    resource: 'https://analysis.windows.net/powerbi/api'
  },
  success: data => {
    console.log(data.access_token)
  },
  error: (xhr, textStatus, error) => {
    console.log('rr', error)
  }
});

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

Sending data from the View to the Controller using AJAX in Laravel 5

Data I have some data stored in a variable var info = []; info['upnp_enabled'] = $("#upnp-switch").val(); When I console.log(info);, the output shows [upnp_enabled: "true"] Ajax I attempted to send a PUT request to my Cont ...

Tips for selecting a specific item in a list using onClick while iterating through a JSON array in React

I have a unique JSON file filled with an array of objects, each containing a "Question" and "Answer" pair (I am working on creating an FAQ section). My current task involves mapping through this array to display the list of questions, a process that is fun ...

Achieving a Transparent Flash overlay on a website without hindering its usability (attention, interaction, form submissions, etc.)

Currently, we are attempting to overlay a transparent flash on top of an iframe which loads external websites. Is there a method to configure the page in a way that allows the transparent flash to be displayed while still allowing interaction with the und ...

How to Utilize Custom Component Tag Names in CSS with Vue.js 2?

<template> <header> <hamburger></hamburger> <app-title></app-title> <lives></lives> </header> </template> <script> export default { name: 'Titlebar& ...

What is the correct way to securely send the username and password from a ReactJS frontend to the backend for authentication?

My React application includes an onChange function on a form that collects username and password. Upon submission, the username and password are sent to the server side using redux dispatch in Node.js. On the server side, I am authenticating the credentia ...

Querying MongoDB with a JavaScript file for formatting datetime values

I am utilizing mongodb3.0.5 and my database collection appears as follows: { "_id" : "xxxxxxxxxxxxxxx", "SchoolId" : 1, "ActivationTimestamp" : ISODate("2015-09-22T13:01:58.000Z"), "PersonDetails" : [ { "Name" : "John" ...

Greetings: Obtaining an array of text within the <td> tags

Here is the HTML Source: <td bgcolor="#ffffbb" colspan=2><font face="Verdana" size=1>2644-3/4<br>QPSK<br><font color="darkgreen">&nbsp;&nbsp;301</font> - 4864</td> I am looking to extract text array wit ...

JavaScript: Populating an Array with Image URLs Using a Loop

My image gallery project has hit a roadblock and my JavaScript skills are not up to par. Maybe it's time to brush up on the basics with a good book from the library. Here's what I want to achieve: 1. Create an array of URL's for each imag ...

Generating an HTML table with JSON data in JavaScript

I'm still struggling with JavaScript as a beginner, so please bear with me and provide guidance step by step. Also, try to avoid overwhelming the comments with links as it confuses me. This is an attempt to bypass the CORS issue. <!D ...

Tips for preventing Django template from showing up prior to VueJS rendering

I am currently facing an issue with rendering a Django template using VueJs through CDN. Upon loading the page, I notice that the raw Django code is displayed initially before being rendered by VueJs, which typically takes less than a second. To fetch dat ...

What is the best way to send $(this) to a function?

Here is my code snippet: $(document).ready(function(){ var hCount = 0, eCount = 0, nCount = 0, mCount = 0; $("#head").click(function() { var pPos = calculatePosition(hCount); $(this).animate({left:pPos+"px"}, ...

In order to use Vue3 with Vite, it is necessary to use kebab case tags for custom components, whereas Vue3 CLI allows the

I am working on a project using Vue3 with Vite (on Laravel) that has a Wiki.vue page which loads a "MyContent.vue" component. //On MyContent.vue: <template> <div>content component</div> </template> <script> export default ...

Retrieving an AJAX array POST in Laravel 5 Controller

Below is the structure of my form: <td> <input type="text" name='name[]' class="form-control"/> </td> <td> <input type="text" name='mail[]' class="form-control"/> </td> <td> <select na ...

Clearing the filename in a file type input field using React

When using this input field, only video files are accepted. If any other types of files are uploaded by enabling the "all files" option, an alert will be displayed. While this functionality is working correctly, a problem arises if a non-video file is adde ...

Can an image be uploaded using solely jQuery without relying on PHP?

I have been attempting to upload an image using Ajax/jquery without refreshing the page and also without relying on php in the back-end. After extensive searching, all solutions I found involved php on the server side, but my requirement is to avoid using ...

Tips on finding a JavaScript file using Google search

After releasing my jQuery plugin, I've noticed an increase in downloads. However, I'm curious to know where exactly it is being utilized. One idea I had was to search for the .js or .css file, potentially even looking at folder names. Is there a ...

The presence of Vue refs is evident, though accessing refs[key] results in an

I am facing an issue with dynamically rendered checkboxes through a v-for loop. I have set the reference equal to a checkbox-specific id, but when I try to access this reference[id] in mounted(), it returns undefined. Here is the code snippet: let id = t ...

Invoke actions when clicking outside of components

Currently, I have a HeaderSubmenu component that is designed to show/hide a drop-down menu when a specific button is clicked. However, I am now trying to implement a solution where if the user clicks anywhere else in the application other than on this drop ...

"Effortlessly Load Content in Drupal7 Using jQuery AJAX without Refreshing the

I am currently in the process of getting an AJAX script to function properly on my webpage, which is built using Drupal 7. The objective is for the content of the page to load when one of the menu links is clicked, without refreshing the entire page (as th ...

Modifying the <TypescriptModuleKind> setting for typescript transpilation in project.csproj is not supported in Visual Studio 2017

I recently encountered an issue with changing the module kind used by the transpiler in Visual Studio. Despite updating the <TypescriptModuleKind> in the project's project.csproj file from commonjs to AMD, the transpiler still defaults to using ...