The NextJS API is now pointing to the index.js file rather than the [id].js file

I am currently setting up an API in NextJS. In my /classes folder, I have index.js and [id].js files.

The purpose of /classes/ is to retrieve all classes from the database or add a new class. The purpose of /classes/[id] is to fetch a specific class, update it, or delete it. However, I am facing an issue where trying to get a class by id is returning all classes from the index.js file. Any suggestions on what might be missing?

index.js

if (req.method === 'GET') {
  try {
    console.log('in index get')
    const allClasses = await db.collection('classes').orderBy('name').get()
    const classes = allClasses.docs.map((doc) => {
      return {
        id: doc.id,
        ...doc.data()
      }
    })
    res.status(200).json(classes)
  } catch (error) {
    res.status(400).json({
      error: error.message
    })
  }
} else if (req.method === "POST") {
  try {
    await db.collection('classes').add({
      ...req.body,
      lastUpdated: new Date().toISOString()
    })
    res.status(200).json({
      message: 'New Class Created'
    })
  } catch (e) {
    res.status(500).json({
      error: 'There was an error adding class'
    })
  }
}

[id].js

switch (method) {
  case 'GET':
    try {
      console.log('in id get')
      const classById = await db.collection('classes').doc(id).get().data()
      res.status(200).json(classById)
    } catch (error) {
      res.status(400).json({
        error: `Class does not exist`
      })
    }

    break;
  case 'DELETE':
    try {
      await db.collection('classes').doc(id).delete()
      res.status(200).json({
        message: 'Class Deleted Successfully'
      })
    } catch (error) {
      res.status(400).json({
        error: `Class does not exist`
      })
    }
    break;
  case 'PUT':
    try {
      await db.collection('classes').doc(id).update({
        ...req.body,
        lastUpdated: new Date().toISOString()
      })
      res.status(200).json({
        message: 'Class Updated Successfully'
      })
    } catch (error) {
      res.status(400).json({
        error: `Class does not exist`
      })
    }
    break;
  default:
    res.setHeader('Allow', ['GET', 'PUT', 'DELETE'])
    res.status(405).end(`Method ${method} Not Allowed`)
    break;
}

Answer №1

Based on your feedback

{{server}}/data/courses/?code=LKDF87HGS891LKSJF9

Consider using this approach:

{{server}}/data/courses/LKDF87HGS891LKSJF9

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

How to dynamically insert elements into the HTML page using Angular

When my page first loads, it looks like this <body> <div class="col-md-12" id="dataPanes"> <div class="row dataPane"> Chunk of html elements </div> </div> <div class"col-md-12 text-right"> <input type="butt ...

When I include the alert('it is functioning now'); function, it operates correctly, however, it is not desired in this situation

After adding alert('now it works') to this function, it only functions correctly. However, I do not want to include this alert but the function fails without it. function a() { var ac = document.forms["myForm"]["textfield"].value; $.ajax ...

Insects featuring a button and tooltip duo creating a captivating "pull-effect"

Why is the button pulling when I move the cursor over a camera? Is there a way to solve this issue? <div class="input-group-btn advanced-group"> <button class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Send Imag ...

Fetching from the same origin results in a null comparison issue due to HTTP CORS restrictions

Encountering an issue where a simple same-origin fetch("fetch.xml") call fails, resulting in a console error message Access to fetch at 'http://127.0.0.1:8000/fetch.xml' from origin 'null' has been blocked by CORS policy: Th ...

Exploring the methods of accessing $scope within an AngularJS directive

My custom directive is designed for handling form controls like input, select, and radio buttons. Each input has a default value set, and if the corresponding value exists in $scope.answers, it should be displayed in the input box. The code snippet below ...

What is preventing me from integrating angular-cookies into my application?

I'm struggling to resolve this issue where I can't seem to make it work. My aim is to integrate NgCookies (angular-cookies) into my application, but all I'm encountering are errors. This is what I currently have: JS files being included: ...

SignalR does not include cookies in the connection request

While working on a web application using ASP.NET Web API and SignalR, I encountered an issue that is proving to be quite challenging despite my understanding of HTTP. Currently, I have successfully set a cookie on all AJAX requests to the API, and subsequ ...

What could be causing my ng-grid footer to refuse to align with the bottom border?

Currently utilizing ng-grid and various AngularJS UI Bootstrap components on my website, I have encountered a recurring issue. By diligently investigating, I have successfully replicated the problem. Access the Plunker demonstration through this link. The ...

Using an AJAX request to edit a record directly without the need for a

When updating a record, I typically utilize CRUD operations and a store setup similar to the following: storeId: 'storeId', model: 'model', pageSize: 10, autoLoad: true, proxy: { typ ...

Storing numerous JSON records into an array by parsing them from a file

As a beginner in JS programming, I have a question that may seem trivial. Despite hours of searching online, I haven't been able to find a solution that works for me. I am dealing with multiple JSON feeds where each URL provides a multilayer JSON rec ...

Refresh the page and navigate to the last active tab using PHP and jQuery jTable

After a user clicks the submit button on a jquery-jtable form, I am trying to reload the page and navigate to the tab that was active before the reload. However, my current solution only reloads the page without navigating to the previous tab. The tabs are ...

Creating a monorepo project in JavaScript that mimics the structure of Visual Studio projects

When working on a typical .NET Core project (with Visual Studio 2019), the structure typically looks like this: Example/ |-- Example.Common/ | |-- FileExample1.cs | |-- FileExample2.cs | `-- Example.Common.csproj |-- Example.WebAPI/ | |-- Control ...

Testing for the presence of a child element within a parent component in React

Below is the structure of my component: const Parent = (props) => { return <div>{props.children}</div>; }; const Child1 = (props) => { return <h2>child 1</h2>; }; const Child2 = (props) => { return <h2>child 2 ...

Clicking on the image in an owl carousel slider does not trigger the onsen template page to load

I am experiencing an issue with my owl carousel slider while calling an API for page content on image click. I have implemented an onsen template page using ng-click on image, but it only works for the first image click. Subsequent images do not call the o ...

Async/Await mishap

Could someone please explain why the code below is printing a blank result? I was expecting it to print "done" since I thought the await keyword would make the program wait for the promise to be resolved. Appreciate any help provided! let message = &apos ...

Set values for scope variables that are created dynamically

I am currently working on a solution to toggle dynamically generated rows of data. I have attempted using ng-init and passing it to a function, but I seem to be making a mistake somewhere and struggling to understand if this is even feasible. The issue see ...

Phone Validation for Contact Form 7

Recently, I was tasked with creating a landing page for a job interview. The challenge was to include validation on the phone number field so that it has to be between 9 and 10 numbers in length, along with another validation requiring the phone number t ...

Why does my camera suddenly switch to a rear-facing view when I begin my Zoom meeting?

I am facing an issue with my camera function where it initially starts off facing backwards, but as soon as I perform the first scroll, it flips around and works correctly. Please note that I am a beginner in coding. Kindly be aware that there is addition ...

I am curious about the inner workings of the `createApplication()` function in the ExpressJS source code. Can you shed some light on

My goal is to deeply comprehend the inner workings of the Express library, step by step. From what I gather, when we import and invoke the 'express()' function in our codebase, the execution flow navigates to the ExpressJS library and searches fo ...

Tips for identifying a webpage and making class modifications based on it

I am working on a customized bar with 4 distinct parts. Each part corresponds to a different page on the website. I want each part of the bar to change color based on which page the user is currently browsing. For example, if the user is on page A, I want ...