簡體   English   中英

在 nextjs 中循環 getServerSideProps

[英]Loop getServerSideProps in nextjs

我正在學習 nextjs,我正在嘗試從數據庫中獲取數據並將其顯示在索引頁面中,但是當我運行 getServerSideProps function 時,它會循環並不斷向我發送終端中的數據,我該如何解決和在索引頁顯示數據? 謝謝你們

代碼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 
     } 
  }
  
}

代碼 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("/");  
}

您不應在 API 響應中重定向,只需返回 JSON。

res.redirect("/");

應該變成:

res.status(200).json(results);

我認為正在發生的事情是服務器在每次查詢后不斷重定向到/ ,因此存在無限循環來獲取數據。

另外,你應該回來

return {
  props: {
    utenti: data
  }
}

來自getServerSideProps

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM