错误:使用 nextjs getserversideprops 连接 ECONNREFUSED ::1:5000

Abd*_*hdi 0 typescript axios next.js

我正在尝试连接到 localhost:5000 上的 api,当从邮递员或浏览器调用时它可以完美工作,但在 nextjs getserverside props 中调用时不起作用:

mport { useEffect,useState } from "react";
 import { GetStaticProps, GetStaticPaths, GetServerSideProps } from 'next'
 import Axios, {AxiosResponse} from 'axios'
interface Data{
    labels: string[],
    series:number[][]
}
function Chart(props) {
const [data,setData]= useState<Data>()
    useEffect(()=>{
        console.log(props)
 let fetchedData = {
    labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
    series: [
     [6,5,3,2,1]
    ]
  }
  
  setData(fetchedData)
    },[])
    
      
       new Chartist.Line('.ct-chart', data);
      useEffect(() => {
        setTimeout(() => {
          /* do stuff */
        }, );
      }, []);
    return (
        <>
        <div className="ibox ">
        <div className="ibox-title">
            <h5>Simple line chart
            </h5>
        </div>
        <div className="ct-chart ct-perfect-fourth"></div>
    </div>
        </>
        
    )
  }
  

  export const getServerSideProps: GetServerSideProps = async (context) =>{try {
    const res = await Axios.get("http://localhost:5000/api/charts/2")
  
   let data= await res.data;
    return { props: { data } }
    } catch (err) {
    console.log(err)
    }}
     
export default Chart
Run Code Online (Sandbox Code Playgroud)

它返回此错误:

  port: 5000,
  address: '::1',
  syscall: 'connect',
  code: 'ECONNREFUSED',
  errno: -4078,
  path: '/api/charts/2',
  _currentUrl: 'http://localhost:5000/api/charts/2',
Run Code Online (Sandbox Code Playgroud)

我看不出它为什么不能工作的任何原因,特别是它在邮递员中工作

Ped*_*ram 6

节点 >= 18

如果您使用的是18 或更高版本,并且在调用或等操作中遇到node此错误:buildgetServerSidePropsapi

cause: Error: connect ECONNREFUSED ::1:8000
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1487:16) {
    errno: -4078,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '::1',
    port: 8000
  }
Run Code Online (Sandbox Code Playgroud)

就我而言,我更改了api地址localhost:8000 => 127.0.0.1:8000并解决了问题!

不要降级node来解决这个问题!