What could be causing the malfunction of this universal API endpoint?

Lately, I've been diving into learning NextJS API routes and NodeJS. While I have successfully grasped the concept of creating dynamic routes, there are a few hurdles I'm facing -

Let's take a look at my api/matches.js file.

// Next.js API route support: https://nextjs.org/docs/api-routes/introduction

export default async function handler(req, res) {
  const response = await fetch(`https://exampleapi.com/?&token=# `)
  const jsonData = await response.json();
  res.status(200).json(jsonData);

}

Now, I have another dynamic route in this API which retrieves matches based on a match slug, hence the file name /api/matches/[...matchslug].js

export default async function handler(req, res) {
const  page  = req.query.matchslug
const response = await fetch(`https://examleapi.com/?search[slug]=${page}&token=# `)
const jsonData = await response.json();

Although this dynamic route fetches results for a single match when querying matches/exampelmatch, my goal is to figure out a way to

matches/examplematch1/examplematch2

where I can retrieve data for both examplematch1 and examplematch2 simultaneously.

I'm curious if such functionality is achievable and would love to explore it further.

Thank you for taking the time to read through this.

Answer №1

If you're working with the /api/matches/[...matchslug].js example, keep in mind that the value of matchslug is always going to be an array.

Instead of directly passing the page variable to fetch, consider looping through the values in the matchslug array and utilizing Promise.all to make requests for each resource.

Here's how you could potentially set it up (though I haven't tested this code yet):

export default async function handler(req, res) {
  const promiseArray = req.query.matchslug.map(async (slug) => {
    const response = await fetch(`https://examleapi.com/?search[slug]=${slug}&token=# `)
    const jsonData = await response.json();
    return jsonData
  })
  const result = await Promise.all(promiseArray)
  res.status(200).json(result);
}

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

What steps can be taken to choose a particular class when multiple classes share the same name?

Imagine having a table layout like this: <table class="first-table" border="1" width="400px"> <tr> <td><?php echo $row_cond['title']; ?></td> <td><a class="more" href="#" onClick="slideup() ...

ReactJS does not recognize the library mentioned

click here to access the pondjs folder inside node-modulesAfter installing pondjs(https://www.npmjs.com/package/pondjs) using npm install pondjs --save in my react application and confirming its presence in package.json, I encountered an issue in App.js. W ...

Guide to automatically refreshing the page after changing the language in nextjs: Transitioning from clientside to serverside

I have been working on a nextjs app where I retrieve localized data using query parameters ('website.com/data?lang=en'). However, I am facing an issue when users change the app locale. How can I refresh or trigger getServerSideProps/getStaticProp ...

Exploring the capabilities of Redux Toolkit's createEntityAdapter in designing versatile data grids

Seeking guidance on utilizing createEntityAdapter from Redux Toolkit. In my application, I display package information and details using the master/detail feature of the AG Grid library. Packages are loaded initially, followed by fetching detailed data as ...

Transfer attributes, but have exclusions in React

At times, we all have a common practice of wrapping DOM elements in custom components. <CustomComponet id="abc" title="abc" nonDomProp="abc" ...andsoforth /> In this example, the custom component wraps a button with pr ...

Encountering an uncaughtException: Error stating that the module '....nextserverapphomelibworker.js' cannot be located while attempting to utilize pino.transport in Next.js

I recently set up a Next.js project with typescript using create-next-app. Opting for Pino as the logging library, recommended by Next.js, seemed like the logical choice. Initially, when I utilized Pino without incorporating its transport functionality, e ...

Which Express.js template allows direct usage of raw HTML code?

I am in search of a template that utilizes pure HTML without any alterations to the language, similar to Jade but keeping the HTML as is. The reason behind this inquiry is: I prefer the simplicity and clarity of HTML I would like to be able to easily vi ...

Convert individual packages within the node_modules directory to ES5 syntax

I am currently working on an Angular 12 project that needs to be compatible with Internet Explorer. Some of the dependencies in my node_modules folder are non es5. As far as I know, tsc does not affect node_modules and starts evaluating from the main opti ...

Basic HTML code that displays either one or two columns based on the width of the screen

My monitoring website displays dynamic rrd graphs in png format with fixed dimensions. I am looking to adjust the layout based on browser window size - showing the graphs in 1 column if the width is below a certain threshold, and in 2 columns if it exceed ...

Laravel 8 is throwing an error: "ReferenceError: route is not defined"

require('./bootstrap'); require('./ziggy'); window.Vue = require('vue'); const files = require.context('./', true, /\.vue$/i); files.keys().map(key => { return Vue.component(_.last(key.split('/' ...

Utilizing jQuery to manage asynchronous tasks, such as executing AJAX requests, handling promises, and using deferred

Exploring My jQuery Plugins: (function ($, window, document, undefined) { $.fn.loadPageContent = function (url, dataToSend) { url = url || window.location.href; dataToSend = dataToSend ? dataToSend : {}; return $.post(url, data ...

Creating interactive labels in a histogram that update based on the user's input

Currently, I have operational code in place that takes input data and generates a histogram based on set thresholds. When the code is executed, the histogram changes dynamically as the threshold slider is adjusted. However, there seems to be an issue wit ...

Modifying information in a single array in Vue JS has a ripple effect on

I'm really struggling to understand what the ... want with this Vue component! Can someone please help me out? Here is my code: var groupadding = new Vue({ el: '#groupAdd', data:{ currentFullData: [], localData: [] }, method ...

JavaScript providing inaccurate height measurement for an element

Upon loading the page, I am trying to store the height of an element. To achieve this, I have utilized the jQuery "ready" function to establish a callback: var h_top; var h_what; var h_nav; $(".people").ready(function() { h_top = $(".to ...

Toggle among 10 divs, but automatically revert back to the initial div if there is no mouse activity for a short period

My website has 9 links in the header and 10 divs in the body. The first div serves as the main page, while the remaining 9 divs contain different content. I would like to implement a feature where when users hover over the 9 links, it displays one of the 9 ...

What could be causing the malfunction of this Bootstrap button dropdown?

Initially, I attempted using regular HTML for the dropdown button but encountered issues. As a result, I switched to jsfiddle to troubleshoot. Despite my efforts, the dropdown feature still refused to work. If you'd like to take a closer look, here&a ...

What is the reason for my result showing as Object { } rather than MyObj { }?

When utilizing the web development tools console, if a browser object is typed, it will return as "console." > console Console { } > console.log(console) undefined > Console { } This behavior applies to all browser objects. However, when I try ...

Is it common to have numerous operations in a single controller in AngularJS?

<!DOCTYPE html> <html ng-app="myApp" > <head> <title>myApp.html</title> </head> <body ng-controller="myCtrl as vm"> <br><br> <div> <p> I ...

JavaScript now assigns a value of null in place of undefined

When working with JavaScript, it's important to understand that undefined can be reassigned. Because of this, it is recommended to create a self-executing function to ensure that undefined remains undefined. Are there any other values that are loosely ...

What is the process for aligning rows with the selected option from the drop-down menu

Alright, so here's the scenario: I have created a table along with two drop-down filters. The first filter is for selecting the Year, and it offers options like "All", "2023", "2022", and "2021". When I pick a specific year, let's say "2022", onl ...