next.js 错误:使用下一个js getserversideprops连接ECONNREFUSED::1:5000

e0bqpujr  于 2023-02-12  发布在  其他
关注(0)|答案(1)|浏览(153)

我正在尝试连接到localhost:5000上的API,当从 Postman 或浏览器调用时,它可以完美地工作,但当在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

并返回以下错误:

port: 5000,
  address: '::1',
  syscall: 'connect',
  code: 'ECONNREFUSED',
  errno: -4078,
  path: '/api/charts/2',
  _currentUrl: 'http://localhost:5000/api/charts/2',

我看不出有什么理由它不起作用,特别是它在 Postman 身上起作用

72qzrwbm

72qzrwbm1#

节点〉= 18

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

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
  }

在我的例子中,我将api地址从localhost:8000=>127.0.0.1:8000更改为api,问题解决了!

请勿通过降级node来修复此问题!

相关问题