0

so this is the error:

Error [AxiosError]: Request failed with status code 401
at eO (.next/server/chunks/859.js:1:47996)
at IncomingMessage.<anonymous> (.next/server/chunks/859.js:3:9448)
at aN.request (.next/server/chunks/859.js:3:21242)
at async l (.next/server/app/items/page.js:1:8491)
at async a (.next/server/app/items/page.js:1:8595) {
code: 'ERR_BAD_REQUEST',
config: [Object],
request: [ClientRequest],
response: [Object],
status: 401,
constructor: [Function],
toJSON: [Function: toJSON]

It says request failed with 401 status code but, I'm not even using authentication for the app. The error occurs for routes /api/items and /api/items/${id} and both are GET requests.

I am attaching all the relevant code down here. Please help me.

/items

import axios from "axios";
import ItemCard from "@/components/ItemCard";
import { IItem } from "@/models/item.model";
import { getBaseUrl } from "@/lib/getBaseUrl";

const getData = async () => {
  try {
    const baseUrl = getBaseUrl();
    const { data } = await axios.get(`${baseUrl}/api/items`);
    console.log(data);
    // const res = await fetch("/api/items");
    // const data = await res.json();
    // console.log(data);
    return data;
  } catch (e) {
    console.log(e);
  }
};

const Items = async () => {
  try {
    const items: IItem[] = await getData();
    if (!items) {
      return <div>No items found</div>;
    }

    return (
      <div className="min-h-screen h-fit w-full bg-black flex justify-center">
        <div className="grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 justify-center">
          {items.map((i: IItem) => (
            <ItemCard item={i} key={i._id} />
          ))}
        </div>
      </div>
    );
  } catch (error) {
    console.error("Error loading items:", error);
    return <div>Error loading items. Please try again later.</div>;
  }
};

export default Items;

/items/${id}

import { IItem } from "@/models/item.model";
import axios from "axios";
import { getBaseUrl } from "@/lib/getBaseUrl";

const getData = async (id: string) => {
  try {
    // const { data } = await axios.get(`/api/items/${id}`);
    // const res = await fetch(
    //   `${process.env.NEXT_PUBLIC_BACKEND_URL}/api/items/${id}`,
    //   { method: "GET" }
    // );
    // const data = await res.json();
    const baseUrl = getBaseUrl();

    const { data } = await axios.get(`${baseUrl}/api/items/${id}`);

    return data;
  } catch (e) {
    console.log(e);
  }
};

const ItemDetails = async ({ params }: { params: Promise<{ id: string }> }) => {
  const { id } = await params;
  const item: IItem = await getData(id);
  if (!item) {
    return (
      <div className="min-h-screen flex items-center justify-center text-white">
        Item not found
      </div>
    );
  }

  const date = new Date(item.date);
  return (
         {//remaining jsx here}
  );
};

export default ItemDetails;

/api/items

export const GET = async () => {
  try {
    await connectToDb();
    console.log("inside get request");
    const allItems = await Item.find({});
    console.log("Successfully fetched items:", allItems.length);
    return NextResponse.json(allItems);
  } catch (error) {
    console.error("Error in GET /api/items:", error);
    return NextResponse.json(
      { error: "Failed to fetch items" },
      { status: 500 }
    );
  }
};

/api/items/${id}

export const GET = async (request: NextRequest) => {
  const id = request.nextUrl.pathname.split("/").pop();
  try {
    connectToDb();
    const item = await Item.findById(id);
    return NextResponse.json(item);
  } catch (error) {
    console.log(error);
  }
};

The POST request works so there's no problem in connecting to the Mongo database, I suppose.

Here is the live website replicating the issue And also, here is the Github

2
  • Can you try by moving the GET api request to client component. (move the whole code in the items page to another new component and add "use client" on the top) Commented Dec 28, 2024 at 1:01
  • Found the error, it was not anything related to either the api nor the page. It was coming from the getBaseUrl() utility I'm using. It was basically not getting the correct base url and hence the request was failing. Thanks for trying to help though! Commented Dec 28, 2024 at 17:21

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.