Accessing API using Next.js 14

I am facing an issue with the following code which is written in next.js. The error displayed on the console is:

GET http://localhost:3000/products/porducts.json 404 (not found)

Additionally, I'm encountering this error:

Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
fetch("/products/products.json")
    .then((response) => response.json())
    .then((data) => console.log(data));

I have tried multiple solutions to fix this problem, including seeking help from chatGPT, but so far, none of my attempts have been successful.

fetch("/products/products.json")
    .then((response) => response.json())
    .then((data) => console.log(data));

Answer №1

Make sure to keep the products.json file in the /public directory as it is a static file. This means that the correct path would be /public/products/products.json.

If you mistakenly place the products.json file in the /app/products/products.json folder, it will not be accessible. Remember that Next.js only reads files from the app folder like page.jsx, not-found.jsx, or route.js. The error message

Unexpected token '<' is not a valid JSON
occurs because trying to retrieve /products/products.json will lead to loading the not-found page instead.

Answer №2

Amanda. As of Nextjs 13 and beyond, the implementation of the app router was introduced, offering a different routing approach compared to the traditional pages router.

Developers now have the flexibility to choose between the app router, the pages router, or utilize both simultaneously. While the app router is newer, it does not render the pages router obsolete or inferior.

To start integrating the app router into your project, create a folder named app/ at the project root or within the src/ directory.

If you opt for the traditional method using the pages router, establish a directory labeled pages/ either in the project root or inside the src/ directory.

Based on the screenshot provided, it seems that your Nextjs application relies on the app router since your code resides within the app/ directory.

In the context of the app router, only specific files are exposed to the browsing experience, unlike the pages router where any content placed within automatically becomes accessible through the browser's URL address bar.

Given that you are currently attempting to fetch a JSON file from a client component, this action will not yield results due to the aforementioned regulations regarding the app directory.Only designated files (specifically those titled: page.tsx) are served for this purpose.

To successfully access the JSON file, relocate it from the app directory to the public/ directory.

After making this adjustment, the file can be reached via:

http://localhost:3000/products.json

Therefore, modify your code snippet from:

fetch("/products/products.json")
    .then((response) => response.json())
    .then((data) => console.log(data));

to:

fetch("/products.json")
    .then((response) => response.json())
    .then((data) => console.log(data));

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

I want to locate every child that appears after the <body> element, and extract the HTML of the element containing a specific class within it

It may sound a bit confusing at first, but essentially I have some dynamically generated HTML that resembles the following: <body> <div class="component" id="465a496s5498"> <div class="a-container"> <div class="random-div"> ...

Is it possible to connect to a Node server from outside the network if the application is only listening on 'localhost'?

When utilizing the Express framework and we implement app.listen(port), the app will be located at localhost:port/ On a local machine, it is clear how to access this address using a local browser running on the same machine. Even clients within the same n ...

Retrieving values using the jQuery .each() function and passing them to an AJAX request

Is it possible to set jQuery AJAX outside of .each in the script provided below? $('#btnUpdate').click(function() { $('#result').html(''); $('.moduleIDInput').each(function() { var uid = $(this). ...

Cease the audio from playing unless you are actively hovering over the image

Is there a way to make the sound stop playing when you are not actively hovering over the picture? Any suggestions on how to achieve this would be greatly appreciated! imgarr[i].onmouseout=function(){ this.setAttribute('src',this.getAttribu ...

Is it possible to use multiple schemas for one collection name?

I am currently working on creating different schemas for a single collection, such as User or subUser. I aim to store both User and subuser data in the same collection but with different schemas. Here is an example of my schema file: export const AryaSchem ...

Trigger a jQuery function upon clicking a button

I am attempting to create a jQuery function that can be called independently, and then trigger the function when a click event occurs. Below is the code I have put together: HTML: <input type="text" class="form-control email_input" name='email&ap ...

Encountering a type error while trying to read dummy data, as the map function is not

I am currently working on fetching dummy data from a URL in my component using TS and Next.js. Unfortunately, I encountered an error type that I am unable to diagnose. typings.d.ts: export type Themen = { id: number; title: string; description: string; ...

Struggled to Find a Solution for Code Alignment

Is there a tool or software that can align different types of codes with just one click? I've tried using the Code alignment plugin in Notepad++, but it hasn't been effective. For example, when aligning HTML code using tags, I couldn't find ...

Expand the <div> by clicking on it, then hover away to return it to its normal size

One interesting feature I have on my website is a <div> that expands when clicked, and returns to normal size with another click. However, I am looking for something a bit different... What I want is for the <div> (with the class name .topHead ...

What are some techniques for obtaining the second duplicate value from a JSON Array in a React JS application by utilizing lodash?

Currently, I am tackling a project that requires me to eliminate duplicate values from a JSON array object in react JS with specific criteria. My initial attempt was to use the _.uniqBy method, but it only retained the first value from each set of duplicat ...

Eliminate the Jquery Combobox

I've implemented the Jquery Combobox on my website /*! * Combobox Plugin for jQuery, version 0.5.0 * * Copyright 2012, Dell Sala * http://dellsala.com/ * https://github.com/dellsala/Combo-Box-jQuery-Plugin * Dual licensed under the MIT or GPL V ...

Issue encountered with @Nuxt.js/Cloudinary plugin for Media Enhancement: "Access to this endpoint is restricted due to insufficient permissions"

I am currently utilizing the @nuxtjs/cloudinary module based on the module guide and a course video. However, I am encountering an error in the response as follows: Status 403, message: You don't have sufficient permissions to access this endpoint&qu ...

Issue with deploying production build in Next.js causing 404 errors on sub pages

After deploying my Next.js build code to production using the command next export -o outDir, I noticed that only the home page is working. When attempting to access /login, I am receiving a 404 error. Can anyone offer guidance on how to resolve this issu ...

AngularJS special feature: enhance controllers and views by adding notification capabilities

What is the most efficient method for integrating common notification features into necessary controllers in AngularJS? The objective is to establish local notifications that can be effortlessly included or removed from any controller. Key factors includ ...

Having trouble resolving "react-native-screens" from "node_modules eact-navigation-stacklibmoduleviewsStackViewStackViewCard.js"? Here's how to fix it

Here is the command I used for setting up react app routes: npm i react-native-router-flux --save After restarting npm with "npm start," I encountered this error message: Unable to resolve "react-native-screens" from "node_modules\react-navigation- ...

Is there a way to temporarily halt a jQuery animation for 2 seconds before automatically resuming it, without relying on mouse-over or mouse-out triggers?

With just one scrolling image implemented in jQuery, the logos of clients are displayed continuously in a scrolling box with no pauses. Speed can be adjusted easily, but pausing and then resuming the animation after 2 seconds seems to be a challenge whic ...

Select the directory for downloading the file in your REACTJS application

I am working on a code snippet that generates a URL containing a .csv file for downloading. const getCSVURL = async () => { const response = await PerformanceFilterManager.getCSVURL(); setCSVUrl(response); }; This function is triggered by click ...

What is the best way to generate a dynamic slug using dynamic API Routes in Next.js 14?

[I am currently working on obtaining user verification tokens using Dynamic API Routes in the latest version of NextJS-14. For the user verification process, my base route is "/api/auth/verify" in NextJS 4 using the app router. I send a registration link i ...

Stub Node - Constructor Implementation

I've been searching for a solution for quite some time with no success, I have the following code that I want to test: some_script.js var Model = require('./models') exports.tokenizeCard = function (args) { var model = new Model(&apos ...

The componentDidMount lifecycle method of a rendered component in a Route is not being triggered

IMPORTANT: SOLUTION PROVIDED BELOW, NO NEED TO READ THROUGH THE QUESTION I am utilizing the following Router with react-router 4 return ( <Router> <Page> <Route exact path="/" component={HomePage} /> <Route path="/c ...