1

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?

2
  • Your folder structure is quite weird. Are you like using the new Next.js app folder? Commented May 4, 2023 at 21:17
  • no the folder struct is from a template in nextJS :( Commented May 8, 2023 at 9:55

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

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.