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.