Implementing an API route to access a file located within the app directory in Next.js

Struggling with Nextjs has been a challenge for me. Even the most basic tasks seem to elude me. One specific issue I encountered is with an API call that should return 'Logged in' if 'Me' is entered, and display a message from mydata.txt. However, when trying to read the file, it seems to break the functionality. Interestingly, when the code is hardcoded with msg, it works without any issues!

app/api/myapi.js

var fs = require('fs');
export default function handler(req, res) {
  var msg = fs.readFileSync("mydata.txt")
  if(req.body=="Me"){ res.status(200).json({ message: `Logged in` }) }
  else{ res.status(200).json({ message: `Error ${msg}` })  } 
}

Within the index.html file, I attempt to fetch the response and alert it. The content of mydata.txt is currently set as "Not logged in". (mydata.txt resides in the app/api directory, although I also attempted moving it to the root directory.)

The errors encountered are always:

POST 404 (Not Found) VM155:1 Uncaught (in promise) SyntaxError: Unexpected end of JSON input

I experimented with relocating the mydata.txt file to various directories. Surprisingly, when msg was hardcoded, everything worked perfectly.

Answer №1

It appears there may be some confusion between the app router (introduced in NextJS 13) and the page router. These two routers require different styling approaches, as even the official NextJS documentation has separated the instructions based on the type of router being used.

For those utilizing page router:

  • The parent folder should be named page
  • You can simply modify your existing file by changing the path to /pages/api/myapi.js

If you're opting for the app router:

  • The parent folder needs to be named app
  • Your file should be named route.js. In your scenario, the path should be set to /app/api/myapi/route.js
  • Handler functions must be labeled with HTTP verbs such as GET, POST, etc., each one exported individually.
  • Keep in mind that the parameters within the handler functions differ from standard express requests and responses. In TypeScript, the handlers should accept an object with a type of NextRequest, rather than the typical express.Request.

If you wish to proceed with the app router, it will be necessary to make adjustments to your code accordingly.

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

Encountering a Typescript error while attempting to utilize mongoose functions

An example of a User interface is shown below: import {Document} from "mongoose"; export interface IUser extends Document{ email: string; password: string; strategy: string; userId: string; isValidPassword(password: string): ...

Is it possible to integrate a JavaScript library into the Vue prototype?

I've recently integrated ProgressBar.js library into my app, which is built using vue and laravel with laravel mix. After installing ProgressBar.js via npm install, I am unsure how to incorporate it into my .vue files. I'm considering adding it t ...

insert a new DOM element into an array using jQuery

Looking at the code snippet below: a_ajouter = $('.question'); hidden_div.push(a_ajouter); console.log(hidden_div); Upon examining the output in the console, instead of a DOM object being added to the div as intended, it shows &apo ...

Create a function that adds a new div element with a one-of-a-kind identification when

I am currently developing a web application on www.firstusadata.com/cash_flow_test/. The functionality involves two buttons that add products and vendors dynamically. However, the issue I'm facing is that the appended divs do not have unique IDs, maki ...

The XML content fails to display after initiating an AJAX request

Attempting to create an ajax call and accessing a field from the table on the server yields the following: <PushProperty><Status ID = "1"> Success </Status><ResponseID> b3633c9eeb13498f </ResponseID><ID> 9098 & ...

Reposition div when clicked

I have encountered a challenge where I am unable to perform a small task. My goal is to have the position of "div1" change upon clicking on "div2", taking into account that "div2" is nested inside "div1". Additionally, when clicking on "div2" again, "div1" ...

Is there a way to modify the variable in order to switch the font of the heading every second using CSS and JavaScript?

I'm trying to create a heading that changes fonts every second, but I'm having trouble changing the variable to set it to another font. Check out my code here. Despite watching tutorials, everything seemed too confusing. var root = document.q ...

What is the method of utilizing shared services when the controllers do not rely on any shared services?

Let's imagine a scenario where there is a module containing only one factory, which serves as the shared service. angular.module('sharedService', []) .factory('sharedSrv', sharedService) function sharedService() { var numbe ...

Having trouble with the Jquery animate() function?

I recently developed a jQuery animation where clicking on specific buttons triggers a hidden div to slide from left: -650px; to left: 0px;. You can see an example by clicking here. However, I've noticed that when another button is clicked to reveal a ...

Struggling to make PayPal Cordova Plugin function properly in both production and sandbox modes

While using the cordova paypal plugin and switching to sandbox mode, I encountered an error. The plugin can be found at https://github.com/paypal/PayPal-Cordova-Plugin https://i.stack.imgur.com/lD2EH.png Running the plugin in PayPalEnvironmentNoNetwork m ...

Is it possible to refrain from using the object variable name in an ng-repeat loop?

When utilizing an ng-repeat directive to loop through an array, the syntax requires ng-repeat="friend in friends". Inside the template, you can then use the interpolation operator like this {{friend.name}}. Is there a way to directly assign properties to ...

"Discover the steps to seamlessly integrating Snappuzzle with jQuery on your

I am a beginner when it comes to javascript and jquery, and I recently came across the snappuzzle plugin which caught my interest. After visiting snappuzzle plugin, I decided to download and link jQuery, jQuery UI, and the snappuzle.js in my HTML file. I a ...

The absence of the 'Access-Control-Allow-Origin' header is reported even though it is actually present

I have been attempting to send a POST request from one website to my own site. Despite allowing CORS access explicitly, every time I try to make the actual POST request, I am faced with the No 'Access-Control-Allow-Origin' header is present on th ...

Issue: $controller:ctrlreg The controller named 'HeaderCntrl' has not been properly registered

I am encountering an error while working on my AngularJS program. I have defined the controller in a separate file but it keeps saying that the controller is not registered. Can someone please help me understand why this issue is happening? <html n ...

Steps to enable Nodemailer to execute a separate .js script

Currently, I have the main nodejs server file named myserver.js const express = require("express"); const app = express(); const nodemailer = require("nodemailer"); const port = 80; const vectorExpress = require("./node_modules/@ ...

Looking for guidance on implementing a straightforward nested for loop in a Node.js environment

I am facing an issue with my code that is meant to generate a 10x10 grid. Since transitioning to Node.js, I am struggling to make it work correctly due to my synchronous thinking pattern. Currently, the Y values are being assigned directly to 10 for all X ...

Issue with TinyMCE Editor: Inoperative

<script type="text/javascript" src="<your installation path>/tinymce/tinymce.min.js"></script> <script type="text/javascript"> tinymce.init({ selector: "textarea", theme: "modern", plugins: [ "advlist autolink li ...

Utilize AngularJS to Capitalize the First Letter and the Letter Following a Dot (.)

I am seeking a solution to capitalize the first letter in a given string, like so: sumo => Sumo Additionally, I need to capitalize strings in the following format: Dr.ravi kumar => Dr.Ravi kumar Although I have implemented an Angular filter that ...

Is there a way to utilize AJAX to submit a request to a PHP XML-RPC server?

To communicate with my XML-RPC PHP server from a PhoneGap app, I intend to send an XML-RPC request using AJAX. The request should contain the method, parameters, and all necessary details. ...

What is the best way to adjust the screen to display the toggle element when it is opened?

Here is the code I'm currently using to create a toggle button that shows or hides extra content when clicked: $(".toggle .button").click(function() { $(this).next().slideToggle('fast'); }); The issue I am encountering is that if t ...