我正在尝试连接到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 身上起作用
1条答案
按热度按时间72qzrwbm1#
节点〉= 18
如果您使用的是
node
版本18或更高版本,并且在build
或getServerSideProps
中遇到此错误,请调用api
等:在我的例子中,我将
api
地址从localhost:8000
=>
127.0.0.1:8000
更改为api
,问题解决了!请勿通过降级
node
来修复此问题!