MySQL2 with Requests.JSON not fetching properly?
Answered
Chum salmon posted this in #help-forum
Chum salmonOP
I have the following code:
And
I see this same concept on both the NextJS docs, and this video here (https://www.youtube.com/watch?v=aprLiG34b50&t=705s, skip to 9:00).
This works well on their demonstrations, but when I do it, it tries to return [Object object] and I get the error:
Do I have to stringify the data and mess with it to get it to work?
//On server /app/api/findPartsFittingMachine/route.js
const mysql = require('mysql2/promise');
export async function GET(request) {
try {
//Create connection request
let conn = await mysql.createConnection({
host: process.env.ATCREVIVE_DB_HOST,
user: process.env.ATCREVIVE_DB_USER,
password: process.env.ATCREVIVE_DB_PASSWORD,
database: process.env.ATCREVIVE_DB_MAINDB
});
//Get the part number from the search parameters
const searchParams = request.nextUrl.searchParams;
const partNumber = searchParams.get('partNumber');
//Create a query to get all columns from part entries with a matching part number
let query = `SELECT * FROM Part_Entries WHERE number='${partNumber}'`;
//Execute the query
const [results] = await conn.execute(query);
//Disconnect from the database
conn.end();
//Return the results in a response
return new Response.json({results});
}
catch (err) {
return new Response({ error: err },
{
status: 500
});
}
}And
//On server component /app/parts/[slug]/page.js
export async function getData() {
const apiURLEndpoint = `http://localhost:3000/api/findPartsFittingMachine?partNumber=17255-046-010`;
const response = await fetch(apiURLEndpoint);
const res = await response.json();
return res;
}
export default async function Page({ params }) {
let data = await getData();
return <h1>Test</h1>
}I see this same concept on both the NextJS docs, and this video here (https://www.youtube.com/watch?v=aprLiG34b50&t=705s, skip to 9:00).
This works well on their demonstrations, but when I do it, it tries to return [Object object] and I get the error:
SyntaxError: "[object Object]" is not valid JSONDo I have to stringify the data and mess with it to get it to work?
4 Replies
I would log the return of results:
and then maybe
console.log("Results", results);
//Return the results in a response
return new Response.json({results}); //<-- I've not used this method but it seems 'off'?and then maybe
const response = await fetch(apiURLEndpoint);
if (response.ok){
const res = await response.json();
return res;
}@Ray it should be
ts
return Response.json({results});
Chum salmonOP
Oh wow, I've been programming for this long and cannot believe I just called
new on a static function...It works now. Thank you 😄