Error 400: Invalid Request: Issue encountered when swapping code for Asana access token using Next.js

Encountered a 400 Bad Request error while trying to exchange the code for an access token at .

I am unsure of the cause and would appreciate any assistance. Below is the code:

const GetAsanaAccessToken = async (req, res) => {
  const body = {
    grant_type: 'authorization_code',
    client_id: process.env.NEXT_PUBLIC_ASANA_CLIENT_ID,
    client_secret: process.env.ASANA_CLIENT_SECRET,
    redirect_uri: process.env.NEXT_PUBLIC_ASANA_REDIRECT_URI,
    code: req.body.code // The code obtained in the previous flow goes here.
  };
  console.log({ body });
  const url = 'https://app.asana.com/-/oauth_token';
  const response = await fetch(url, {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: JSON.stringify(body)
  })
    .then((res) => {
      console.log({ res });
      return res.json();
    })
    .catch((err) => {
      console.log({ err });
      return err;
    });

  res.status(200).json(response);
};

export default GetAsanaAccessToken; Then { res } will be like this

{
  res: Response {
    size: 0,
    timeout: 0,
    [Symbol(Body internals)]: { body: [PassThrough], disturbed: false, error: null },
    [Symbol(Response internals)]: {
      url: 'https://app.asana.com/-/oauth_token',
      status: 400,
      statusText: 'Bad Request',
      headers: [Headers],
      counter: 0
    }
  }
}

I have also posted this question in the Asana forum without resolution.

Answer №1

This is the reason.

body: JSON.stringify(body)

I replaced the above with the following, and it worked:

body: Object.keys(body)
    .map((key) => `${key}=${encodeURIComponent(body[key])}`)
    .join('&');

The original caused issues because it resulted in:

{"grant_type":"authorization_code","client_id":"xxx","client_secret":"xxx","redirect_uri":"http://localhost:3000/","code":"xxx"}

It worked after adjusting to look like this (with hand encoding of slashes, etc.) instead of the original format:

grant_type=authorization_code&client_id=xxx&client_secret=xxx&redirect_uri=http://localhost:3000/&code=xxx

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

Show concealed content for individuals who do not have javascript enabled

One of the challenges I faced was creating a form with a hidden div section that only appears when a specific element is selected from a list. To achieve this, I utilized CSS to set the display property of the div to 'none' and then used jQuery t ...

The function Jquery .stop does not exist

I am encountering an issue with the magicline.stop function while attempting to implement an underline sliding effect for my navbar. I have tried to troubleshoot the problem but have been unsuccessful so far. Below is the code snippet: <nav class=" ...

When I set the width of my script to 100% in CSS, it causes the width to become distorted

I encountered an issue with my Div Slider that swaps out Divs on click. When I modified the CSS to include the following: .hslide-item {width: 100%}; The script started ignoring the entire div width. I am looking for a solution where the .hslide-item ca ...

What is the process for retrieving user data from Postgresql using axios.get when the data is already stored within the database?

Using auth0 for user sign up, my React app automatically retrieves user information upon logging in and sends a POST request with axios to the backend. The user ID is stored in userId and the user information is stored in currUser. However, upon logout and ...

Problem arises with table nth-child selector following the addition of grid-gap

Our current table looks like this: https://i.sstatic.net/eUyBB.png The first row has a background color and the second row is white - which is correct. Now I would like to align the attributes to the right. I added the following code to the table: .table ...

What is the best method for showcasing various content using a uniform accordion style in React?

What is the most efficient way to display various content within multiple accordions? view image description here This is the current approach I am taking in my project, where shipping information and delivery options will involve different textboxes, labe ...

Updating input value in Vue using JavaScript method

When using JavaScript to set the value of an input in my Vue method, it initially appears to work. However, when I try to save the data, it only saves what was typed before the value was updated by the method. For example, if I type new yor and select "New ...

Can transclusion be achieved while maintaining the directive's scope in Angular?

Can we achieve the following functionality in Angular? <div ng-controller="MainCtrl" ng-init="name='World'"> <test name="Matei">Hello {{name}}!</test> // I expect "Hello Matei" <test name="David">Hello {{name}}!&l ...

Error: Unable to update Ember Array - Property 'destroy' cannot be read because it is undefined

Is there a way to efficiently update an Ember Array so that changes in the array reflect in the view? Take a look at this simplified code snippet - cacheArr: Em.A([]), count: 1, updateFxn: function() { this.incrementProperty(count); devObj = Embe ...

What is causing Puppeteer to not wait?

It's my understanding that in the code await Promise.all(...), the sequence of events should be: First console.log is printed 9-second delay occurs Last console.log is printed How can I adjust the timing of the 3rd print statement to be displayed af ...

Having trouble locating the CSS and JavaScript files within my Spring Maven project

I have a Spring framework application with a Maven project. In addition, I have CSS and JavaScript files under the WEB-INF folder. When attempting to link the JavaScript and CSS files like this: <link rel="stylesheet" href="../allDesign/js/vendor/anims ...

What is a reliable method for automatically refreshing a webpage despite encountering server errors?

I'm working on an HTML+JS web page that refreshes itself automatically every few seconds using http-equiv="refresh". The problem is, sometimes the server returns a 502 "bad gateway" error, preventing the HTML code from loading and causing th ...

Tips for assessing JSON response data from an AJAX form

I am struggling with how to properly structure a question, but I would like to explain my situation. I am using AJAX to send data and receiving JSON in return. Each value in the JSON response represents a status, and I need to test and react based on these ...

Error: Trying to access the 'keyboard' property of an undefined object

I am encountering an error message 'Cannot read property 'keyboard' of undefined' and I'm not sure how to fix it. I just want to check if the keyboard is visible on the screen, but this specific line of code seems to be causing the ...

Is there a way to retrieve a specific item from an array using a different method than just its position with jsRender?

I am currently working on rendering JSON data using jsRender. Take a look at the sample JSON data below: "PageContentList": [ { "ContentId": 51, "Title": "60 seconds with Rick", "ContentMediaTypeList": [ { ...

Unusual outcome observed when inputting a random number into HTML using JavaScript

In my HTML file, I am trying to input a number within 50% of a target level into the "Attribute" field. Here is the code: <!DOCTYPE html> <html> <body> <input type = "number" name = "playerLevel" onchan ...

The transfer of JSON information from View to Controller yields no value

My goal is to create functionality where users can add and delete JQuery tabs with specific model data, and then save this data to a database. I'm attempting to use an ajax call to send JSON data to the controller, but I am encountering an issue where ...

What are the recommended callbacks for initiating ajax calls and managing files/chunks during dropzone chunk uploading?

I am currently working on implementing chunk uploading using dropzone js and php. My main concern is regarding the placement of ajax calls in this process. When dealing with single file uploads, specifying the URL parameter is sufficient. However, when ...

Angularjs allows you to repeat a specific number of elements based on a given number

I am working with an object that is connected to the $scope in my Angularjs application {name: 'Vampire Cafe', rating: 4, review: "Food was good, cafe was a bit dark..."} I want to display the value of the rating by showing a certain number of ...

Dynamic css property implementation in Vue list rendering

I am currently working on creating a carousel-style list of items similar to the iOS native date/time pickers, where the list can be shifted both upwards and downwards. The positioning of each item is determined by the `top` property from a model, which i ...