typescriptpostnext.jszohoapp-router

POST request works when using an online tester but I cannot get it to work in next.js, constantly getting a 405 code


I am working to connect to Zoho Creator to grab some data. I have tested the request on https://reqbin.com/ and it gives me the right response. But I am trying to implement it in a next.js app and when I navigate to http://localhost:3000/api/test I get a:

"This page isn't working at the moment If the problem continues, contact the site owner. HTTP ERROR 405"

Here is my app/api/test/route.tsx ids/tokens replaced with ----------

import { NextResponse } from "next/server";

export async function POST() {
  const url =
    "https://accounts.zoho.com/oauth/v2/token?client_id=---------------&client_secret=---------------&grant_type=refresh_token&refresh_token=------------------------";

  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
  });

  const data = await response.json();

  console.log(data);

  return NextResponse.json(data);
}

I have tested the request in reqbin and the request properly goes through to refresh my token and I get a response of:

{ "access_token": "---------------------------------", "api_domain": "https://www.zohoapis.com", "token_type": "Bearer", "expires_in": 3600 }

But I cannot get past a 405 when running it through my route


Solution

  • When you navigate to a site the browser will always make a GET request, not a POST, but you are expecting a POST in your route handler therefore you receive a 405 Method Not Allowed error.

    If you were to change the handler to a GET and you will see the route getting hit and it will then return the JSON from the request body of the request you fire off in the handler (in case the request is successful, which you currently do not check).

    So the following should work:

    import { NextResponse } from "next/server";
    
    // for the browser to hit this change it from POST() to GET()
    export async function GET() {
      const url =
        "https://accounts.zoho.com/oauth/v2/token?client_id=---------------&client_secret=---------------&grant_type=refresh_token&refresh_token=------------------------";
     
      // Add some error handling try/ catch here...
      const response = await fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
      });
      // Check HTTP result code before deserializing
      const data = await response.json();
    
      console.log(data);
    
      return NextResponse.json(data);
    }