无法使用 UseAxios 构建 Gatsby,它引发错误:UnhandledPromiseRejectionWarning:错误:连接 ECONNREFUSED 127.0.0.1:80

时间:2021-02-15 00:12:04

标签: reactjs axios gatsby

这是我的 404.tsx 页面组件,嗨,我在使用 gatsby build 构建 gatsby 时遇到问题,总是出现此错误,仅供参考,我使用 axios-hooks ,请问如何解决?,但在开发过程中运行良好

public async Task<Data> GetDataAsync() =>
    await
        Observable
            .Using(
                () => new WebsocketClient(Uri),
                ws =>
                    from x in Observable.FromAsync(() => ws.Start())
                    let requestId = Guid.NewGuid()
                    from m in ws.MessageReceived
                    where m.Text.Contains(requestId)
                    select ParseData(m.Text))
            .Take(1)
            .Timeout(TimeSpan.FromSeconds(5.0));

}

1 个答案:

答案 0 :(得分:1)

尝试将其包装在 this 条件中:

import React from 'react';
import { Container, Box, Typography, makeStyles, Grid, useMediaQuery, useTheme } from '@material-ui/core';
import { Helmet } from 'react-helmet';
import { Link } from 'gatsby';
import useAxios from 'axios-hooks';


export default function NotFound404() {
    if(typeof window !=="undefined"){
    const [{ data: latestArticles = {}, loading: loadingLatestArticles }] = useAxios({
        baseURL: process.env.REACT_APP_API_ENDPOINT,
        url: 'latest-articles',
    });
    }
return (
    <Box>
        
    </Box>
);

注意:将条件外的变量定义为空,并在需要时覆盖它。

<块引用>

但它在开发过程中运行良好

通常当某些东西在 gatsby develop 中起作用但在 gatsby build 中不起作用时,如果因为 availability of global objects, such as window or document。您需要记住 gatsby develop 出现在浏览器中,而 gatsby build 出现在 Node 服务器中(其中没有全局对象,因为它们尚未定义),因此代码在两者中的行为会有所不同环境。这个条件:

if(typeof window !=="undefined")

将确保代码在浏览器中呈现,避免在服务器中被触发。