xif
xif

Reputation: 343

Fetching Next.js API Route Returns 404 (Not Found) Error (Serverless and API ?)

I am trying to fetch a Next.js API route in my application, but I am encountering a 404 (Not Found) error. My folder structure is as follows:

src/
  views/
    pages/
      wizard/
        checkout/
          Order.tsx
      api/
        save-data.ts

In my Order.tsx file, I have a function called sendDataToServer:

async function sendDataToServer(data) {
  try {
    const response = await fetch('/views/pages/api/save-data', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });

    if (response.ok) {
      const result = await response.json();
      console.log('Data saved:', result);
    } else {
      console.error('Error saving data:', response.status);
    }
  } catch (error) {
    console.error('Error:', error);
  }
}

In my save-data.ts file, I have the following code:

import { NextApiRequest, NextApiResponse } from 'next';
import { MongoClient } from 'mongodb';

const uri = "mongodb+srv://xxxx:[email protected]/?retryWrites=true&w=majority";

const client = new MongoClient(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

async function saveData(wallet: string, address: string) {
  if (!client.isConnected()) await client.connect();

  const db = client.db('your_database_name');
  const usersCollection = db.collection('users_order');

  await usersCollection.insertOne({ order });
}

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'POST') {
    const { wallet, address } = req.body;

    try {
      await saveData(wallet, address);
      res.status(200).json({ message: 'Data saved successfully' });
    } catch (err) {
      console.error('Error saving data:', err);
      res.status(500).json({ message: 'Error saving data' });
    }
  } else {
    res.status(405).json({ message: 'Method not allowed' });
  }
}

When I call the sendDataToServer function, I get the following error:

Order.tsx:95 POST http://localhost:3000/views/pages/api/save-data/ 404 (Not Found)

I have tried different fetch URLs but still encounter the issue. Can anyone help me understand why I am getting a 404 error when fetching the API route, and how I can fix it?

Upvotes: 1

Views: 1699

Answers (1)

Abílio Azevedo
Abílio Azevedo

Reputation: 33

You just need to move the /pages folder to be right below /src not inside /views

Upvotes: 1

Related Questions