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

Challenge of Hosting a Next.js Application on IIS

Having recently started using the nextjs SSR framework of React js, I encountered a challenge in deploying my app on iis. Despite following the deployment steps diligently, I faced issues along the way. 1- First, I built my app using the npm run build com ...

How can you access a sibling of the parent element of the current element in Jquery?

I'm working on an HTML project where I have a select field. Depending on the option selected, I need to update the price field with the corresponding price fetched using Ajax. Additionally, I want to be able to input multiple rows by clicking on the ...

Mapping nested values from a Typescript object to properties of a JSON object

Within the scope of a current project I am involved in, we have opted for utilizing the Angular toolset identified as formly to dynamically generate our forms. The present configuration of the form is hardcoded into a Typescript object denoted as mockForm ...

I. Discovering the Step-by-Step Guide on Retrieving User Information from Facebook Upon Generating App

I have set up a Facebook login for user registration on my website. However, I am only able to retrieve the profile name and user ID from Facebook. How can I access the email and other user information? Here is the data I am currently receiving from Faceb ...

I encountered an error from DataTables when trying to set the width of the header cells using the original width of the columns

                 Help! I keep getting an error message: DataTable Uncaught TypeError: Cannot read property 'style' of undefined Does anyone have any ideas on how to fix this?   I keep seeing the following error message: Uncaught Typ ...

What is the best approach for accessing values from dynamic or multiple form fields upon submission in React?

In my form, users have the ability to add Textfields in order to include additional items. However, I am facing a challenge when it comes to retrieving these items from the form upon submission. The Textfields are dynamically created by a component functi ...

When searching for live Ajax in PHP CI, the result is not being displayed on the

I'm puzzled as to why, when I enter names in the input field in this code, no results are displayed. Additionally, I'm getting a Json parser error in my console: SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data ...

How can I run a TypeScript function within a JavaScript file?

I am working with a typescript file named file1.ts export function Hello(str: string) { console.log(str); } In addition, I have another file called index.js { require('./some.js'); } Furthermore, there is a script defined in the pack ...

When using Array.prototype.map(callback, thisArg), the second parameter is disregarded

Currently, I am developing a small game using Node.js and aiming to offer support for two different languages. To display the translated lists of various game modes along with their descriptions, I have implemented Array.prototype.map(callback, thisArg). ...

Display a pop-up upon clicking a button

I've created a custom popup form using Flodesk and added the corresponding Javascript Snippet to my website just before the closing head tag. <script> (function(w, d, t, h, s, n) { w.FlodeskObject = n; var fn = function() { (w[n] ...

When JSON.stringify is used to convert an object to JSON, it will result in

I'm having difficulty creating a JSON object for transmission over the network. The particular array I'm dealing with looks like this in the Chrome debugger. event: Array[0] $$hashKey: "02Q" bolFromDB: 1 bolIndoor: null ...

Using HTML and C# to Deliver Emails

I've encountered a challenge with my HTML page that includes a textbox for users to input their email. When the submit button is clicked, an email should be sent to a specific email address defined in the code, and a pop-up box indicating "Email Sent" ...

The response from NextAuth.js signIn function is consistently null

Every time I invoke the authorize callback in NextAuth from my signIn function on my page, I consistently receive an undefined result, regardless of any attempted fixes. Additionally, the page swiftly refreshes with the inclusion of the callbackUrl query. ...

class-validator: ensures the correct number of digits are present in numeric values

Seeking assistance on validating the number of digits for numeric values using class-validator. Specifically, I want my entity to only accept numbers with 6 digits for a certain property. For example: const user1 = new User(); user1.code = 123456 // should ...

Guide on setting up a new NPM and JavaScript project within Visual Studio 2015

Whenever I watch tutorials, they always mention having a "special npm reference" that I seem to be missing. All I can find are the "normal" references (.net assemblies). I also can't locate any project type labeled as pure "Javascript." I am current ...

Dots are used to indicate overflow of title in React Material UI CardHeader

Is there a way to add ellipsis dots to the title in my Cardheader when it exceeds the parent's width (Card width)? Here is what I have attempted so far: card: { width: 275, display: "flex" }, overflowWithDots: { textOverflow: &apo ...

Send the data from a div to a different page using PHP

Is there a way to pass the value displayed in DIV id to another page? The data is retrieved from another page and shown within the given code. <div id="res" style="float: left; Padding-left: 3px; padding-right:13px;line-height: 15px;"> ...... ...

Generating option list from API JSON responses

I am currently developing a news app using React. I have set up my API to fetch data from newsapi.org and my goal is to display the available news source options in a dropdown list within my select component. However, instead of listing all news sources w ...

AngularJS - Utilizing Google's Place Autocomplete API Key

Recently, I started digging into Google's APIs and attempting to integrate the Places Autocomplete API with Angular. Although I'm fairly new to autocomplete features in general, I haven't included the jQuery library in my project yet. I&apos ...

"Complete with Style: Expand Your Horizons with Material-UI

The Autocomplete feature in Material UI is not expanding to the full width of the TextField element. Any suggestions on how to fix this issue? ...