Next.js Discord

Discord Forum

MySQL2 with Requests.JSON not fetching properly?

Answered
Chum salmon posted this in #help-forum
Open in Discord
Chum salmonOP
I have the following code:
//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 JSON
Do I have to stringify the data and mess with it to get it to work?
Answered by Ray
it should be
return Response.json({results});
View full answer

4 Replies

I would log the return of results:
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;
}
@Chum salmon I have the following code: js //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 js //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 JSON` Do I have to stringify the data and mess with it to get it to work?
it should be
return Response.json({results});
Answer
@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 😄