【问题标题】:NextJS: error in getServerSideProps function with axiosNextJS:使用 axios 的 getServerSideProps 函数出错
【发布时间】:2023-02-18 02:37:25
【问题描述】:

在主页(index.js 文件)上,我使用 getServerSideProps 函数

export async function getServerSideProps(context) {
    axios.defaults.headers.common['Lang'] = context.locale
    try {
        const response = await axios.get('/index?limit=8')
        return {
            props: {
                data: response.data
            },
        };
    } catch (error) {
        return {
            props: {
                error: error
            },
        };
    }
}

以前一切正常,但现在开始出错

connect EADDRNOTAVAIL ip:443 - Local (ip:0)

尽管如果您在 useEffect () 中向同一地址发出请求 - 一切正常

尝试升级到版本 12 - 错误仍然存​​在

截屏

【问题讨论】:

  • 我认为不同之处在于您在前端调用 useEffect,从而使用前端的主机,而在 getServerSideProps 函数中,您的代码在 NodeJS 服务器环境中运行,因此您需要准确指定主机而不是/index
  • 主机被正确替换
  • 那是浏览器控制台的屏幕截图吗? getServerSideProps 在 Node.js 环境中的服务器上运行,它不会将错误记录到浏览器的控制台。该错误/失败的请求很可能来自您客户端代码中的其他地方。

标签: reactjs axios next.js


【解决方案1】:

尝试

const response = await axios.get(`https://yourserver.com/index?limit=8`)

如果有效,请将 https://yourserver.com 替换为您的 .env 变量

另外,尝试 console.log 您的变量:

const response = await axios.get('/index?limit=8')
console.log(response)

并检查您的 API 路由是否具有 .get 方法

【讨论】:

  • 错误也是如此。我在问题的文本中添加了一个额外的屏幕
  • 我使用同一主机在本地启动了该网站 - 一切正常
  • 问题是(我认为)你的网址的绝对路径。也许你启用了 CORS
【解决方案2】:

getServerSideProps你必须输入整个网址http://localhost:3000/api/my-end-point

所以我在 nextjs 中有两个 axios 实例。

import Axios from 'axios'

// Use in react component
const ClientAxios = Axios.create({
    baseURL: '/api'
})

// Use in getServerSideProps
const SystemAxios = Axios.create({
    baseURL: 'http://localhost:3000/api'
})

【讨论】:

    猜你喜欢
    • 2022-10-18
    • 2021-04-22
    • 2021-05-14
    • 1970-01-01
    • 2021-07-15
    • 2021-08-10
    • 2021-12-30
    • 1970-01-01
    • 2020-11-13
    相关资源
    最近更新 更多