api returns undefined
Unanswered
Chinese perch posted this in #help-forum
Chinese perchOP
export default function Home() {
const [data, setData] = useState([]);
useEffect(() => {
fetch('/api/get_data')
.then(response => response.json())
.then(datag => {
console.log(datag.res)
const data = datag.res;
setData(data);
});
}, []);I've been struggling for hours
13 Replies
Chinese perchOP
The data is there
import { NextResponse } from 'next/server';
const mysql = require('mysql2');
const db = mysql.createConnection({
host: "...",
user: "..",
password: "...",
database: "...."
});
export async function GET(req: Request) {
if (req.method === 'GET') {
db.connect(async function(err: any) {
if (err) {
return NextResponse.json({ error: err }, { status: 500 });
}
const results = await db.promise().query('SELECT First_name , Last_name FROM student_list');
console.log(results)
return NextResponse.json({ message: "Got data", res: JSON.stringify(results) });
// db.query('SELECT First_name , Last_name FROM student_list', function (err:any, result:any) {
// if (err) return NextResponse.json({ error: err }, { status: 500 });
// return NextResponse.json({ message: 'Got data' ,res: result})
// });
// return NextResponse.json({ message: 'Oops!' });
});
}
return NextResponse.json({})
}^^^ The api ^^^
Chinese perchOP
bump
please
Chinese perchOP
please?
cmon
please
please only bump at most once a day
Chinese perchOP
aight sorry
Shy Albatross
I read something about req.method now being undefined, and indeed you don't have to check this
because you have the method defined explicitly as GET handler - slim chance that this is the issue and you're always returning
if (req.method === 'GET') {because you have the method defined explicitly as GET handler - slim chance that this is the issue and you're always returning
return NextResponse.json({}) so res is indeed undefinedChinese perchOP
Yeah I got it fixed
I got a load of other issues though