Maria Ramirez
Maria Ramirez

Reputation: 19

POST request works with AJAX but not with fetch

I need to make a post call to get a token. I wanted to use fetch but I keep getting a 500 error. (jquery ajax request worked fine, but I am using react and I want to avoid installing jquery just for this). What is the difference here?

AJAX (works fine, I get a token back)

  var settings = {
              "async": false,
              "crossDomain": true,
              "url": "https://api.com/oauth2/token",
              "method": "POST",
              "headers": {
                            "Accept": "application/json",
                            "Content-Type": "application/x-www-form-urlencoded",
                            "cache-control": "no-cache",
                            "Postman-Token": "postmantoken"
              },
              "data": {
                            "client_id": clientId,
                            "client_secret": clientSecret,
                            "grant_type": "password",
                            "username": username,
                            "password": password,
              }
            }
            $.ajax(settings).done(function (response) {
                            aTkn = response.access_token;
            });
            return aTkn;

Fetch: get a 500 error : {error: "invalid_request", error_description: "Object reference not set to an instance of an object."} error: "invalid_request" error_description: "Object reference not set to an instance of an object."

    fetch("https://api.com/oauth2/token", {
     crossDomain:true,
     method: 'post',
     headers: {  "Accept": "application/json",
                  "Content-Type": "application/x-www-form-urlencoded",
                  "cache-control": "no-cache",
                  "Postman-Token": postmantoken},
     body:{
       "client_id": clientId,
       "client_secret": clientSecreet,
       "grant_type": "password",
       "username": username,
       "password": password,
     }
    }).then((data)=>{debugger})

Upvotes: 1

Views: 1457

Answers (1)

chrisg86
chrisg86

Reputation: 11907

The data you are passing to fetch must be stringified, otherwise something like [object Object] will be passed in:

fetch("https://api.com/oauth2/token", {
    crossDomain: true,
    method: 'post',
    headers: {
        "Accept": "application/json",
        "Content-Type": "application/x-www-form-urlencoded",
        "cache-control": "no-cache",
        "Postman-Token": postmantoken
    },
    body: JSON.stringify({
        "client_id": clientId,
        "client_secret": clientSecreet,
        "grant_type": "password",
        "username": username,
        "password": password,
    })
}).then((data) => { debugger })

Hope this helps!

Upvotes: 1

Related Questions