Trying to make a GET Request - please help
Unanswered
Airedale Terrier posted this in #help-forum
Airedale TerrierOP
This is my /app/api/concept-display/route.js file in NextJS:
And this is in my component:
I get this error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
Could anyone please help me see what's going wrong?
Thank you
import { MongoClient } from "mongodb";
import { NextResponse } from "next/server";
export async function GET(request) {
if (request.method === "GET") {
let client;
try {
client = await MongoClient.connect(
"mongodb+srv://XXX:YYY@cluster0.6ap8sjr.mongodb.net/adv-prog?retryWrites=true&w=majority"
);
console.log("connected to db");
} catch (error) {
return new NextResponse({
body: JSON.stringify({
message: "Could not connect to the database.",
}),
status: 500,
headers: { "Content-Type": "application/json" },
});
}
const db = client.db();
try {
const result = await db.collection("concepts").find().toArray();
console.log("got result from db - before conversion: ", result);
const jsonData = JSON.stringify(result);
console.log("got result from db - converted to json: ", jsonData);
return new NextResponse({
body: jsonData,
status: 200,
headers: { "Content-Type": "application/json" },
});
} catch (error) {
return new NextResponse({
body: JSON.stringify({ message: "Storing concept failed." }),
status: 500,
headers: { "Content-Type": "application/json" },
});
}
} else {
return new NextResponse({
body: JSON.stringify({ message: "Method Not Allowed" }),
status: 405,
headers: { "Content-Type": "application/json" },
});
}
}And this is in my component:
useEffect(() => {
const fetchConceptData = async () => {
const res = await fetch("/api/concept-display");
const data = await res.json();
setConceptData(data);
};
fetchConceptData();
}, []);I get this error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
Could anyone please help me see what's going wrong?
Thank you
1 Reply
to simplify things you may want to use
NextResponse.json( but is the error on the useEffect and that res.json