i am learning nextjs and i am trying to get the data from the db and show it in the index page, but when i run the getServerSideProps function it goes in a loop and keeps sending me the data in the terminal, how can I solve and show the data in the index page? thank you all
code index.js:
import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
export default function Home({utenti}) {
return (
<>
<form method="POST" action='/api/sendInfo'>
<label>Nome</label>
<input type="text" name="nome"></input>
<label>Cognome</label>
<input type="text" name="cognome"></input>
<label>Email</label>
<input type="email" name="email"></input>
<button type="submit">Invia</button>
</form>
<div>
<p>Select Utenti</p>
<button type="submit" action = '/api/getInfo' method="GET"> prendi utenti</button>
</div>
</>
)
}
export async function getServerSideProps () {
// Fetch data from external API
const res = await fetch('http:127.0.0.1:3000/api/getInfo')
const data = await res.json()
console.log ("Questi sono i data");
console.log (data);
// res.json(data)
// Pass data to the page via props
return {
utenti: {
utenti: data
}
}
}
code http:127.0.0.1:3000/api/getInfo:
import connection from "../../db";
export default async(req, res) => {
try{
const query = 'SELECT * FROM Utenti'
const result = await connection.query(
query,
);
console.log(result);
}catch(err){
console.log(err);
}
res.redirect("/");
}
You shouldn't be redirecting in your API response, just return the JSON.
res.redirect("/");
should become:
res.status(200).json(results);
I think what is happening is the server keeps redirecting to /
after each query, so there's a infinite loop of fetching the data.
Also, you should be returning
return {
props: {
utenti: data
}
}
from getServerSideProps
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.