Envato API: Get Bearer Token API

Hey There,

I am trying to integrate authenticate users with envato api. So Only my client at envato could read document online.

I have created an App with Envato APIs and got client_id and secret. I am trying to authenticate via Javascript fetchjs. But I am getting error as below:

Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://mydomain.com’ is therefore not allowed access. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

here is the code:

export async function login (code) {
  const request = {
    grant_type: 'authorization_code',
    client_id: envato.clientId,
    code: code,
    client_secret: envato.clientSecret
  }
  console.log(request, `${envato.apiUrl}/token`)
  let response = await fetch(`${envato.apiUrl}/token`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
    body: JSON.stringify(request)
  })

  return response.json()
}

Your help/guidance much appreciated!

Regards,

I have also tried with no-cors as well:

export async function login (code) {
  const request = {
    grant_type: 'authorization_code',
    client_id: envato.clientId,
    code: code,
    client_secret: envato.clientSecret
  }
  console.log(request, `${envato.apiUrl}/token`)
  let response = await fetch(`${envato.apiUrl}/token`, {
    method: 'POST',
    mode: 'no-cors',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
    body: JSON.stringify(request)
  })

  return response.json()
}

That gives me 400 error with https://api.envato.com/token.

Hey Folks,

I got the solution finally.

This is how it does work.

export async function login (code) {
  const request = {
    grant_type: 'authorization_code',
    client_id: envato.clientId,
    code: code,
    client_secret: envato.clientSecret
  }
  const formBody = Object.keys(request).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(request[key])).join('&')
  let response = await fetch(`${envato.apiUrl}/token`, {
    method: 'POST',
    // mode: 'no-cors',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: formBody
  })
  return response.json()
}

Thank you,