向 api 发送 get 请求时,nextjs geinitialProps 发生 read ECONNRESET 错误

Raj*_*sia 9 node.js reactjs axios next.js

当我在 _app.js 文件的 getInitialPros 中使用 axios 发送 get 请求时,next.js 应用程序中出现此错误。

 if (typeof window === "undefined") {
    // user = await checkAuth(ctx);

    // const token = ctx.req.headers.cookie;

    console.log("TOKEN", ctx.req.headers);

    if (ctx.req && ctx.req.headers.cookie) {
      try {
        res = await axiosClient("get", { cookie: ctx.req.headers.cookie }).get(
          "/auth/currentuser"
        );

        user = res.data;
        console.log("USER IN SERVER SIDE", user);
        ctx.store.dispatch(setAuthenticatedUser(res.data));
      } catch (err) {
        console.log("ERROR in APP", err);
        // console.log("USER FOUND IN APP.JS", res.data);
        ctx.store.dispatch(removeAuthenticatedUser());
      }
    }
  } else {
    try {
      res = await axiosClient("get").get("/auth/currentuser");

      user = res.data;
      // await checkAuth(ctx);

      // await checkAuth(ctx,)
      console.log("IN CLIENT", res.data);
    } catch (err) {}
  }
Run Code Online (Sandbox Code Playgroud)

这个错误是在刷新页面时发生的,但它只发生在服务器端,而不是客户端。

ERROR in APP Error: read ECONNRESET
        at TLSWrap.onStreamRead (internal/stream_base_commons.js:205:27) {
      errno: 'ECONNRESET',
      code: 'ECONNRESET',
      syscall: 'read',
      config: {
        url: '/auth/currentuser',
        method: 'get',
        headers: {
          Accept: 'application/json, text/plain, */*',
          cookie: 'token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1ZjNhYTJlMmQxN2YxMzAxYTA0NGUxYTIiLCJpYXQiOjE1OTgyODUyMDMsImV4cCI6MTU5ODI4ODgwM30.qtaW-D9P6tJHzL1uHZs3wlzF39UPVkPTLEieuqaVEJY',
          'User-Agent': 'axios/0.19.2'
        },
        baseURL: 'https://tatkaladda.com/api/',
        transformRequest: [ [Function: transformRequest] ],
        transformResponse: [ [Function: transformResponse] ],
        timeout: 0,
        adapter: [Function: httpAdapter],
        xsrfCookieName: 'XSRF-TOKEN',
        xsrfHeaderName: 'X-XSRF-TOKEN',
        maxContentLength: -1,
        validateStatus: [Function: validateStatus],
        data: undefined
      },
Run Code Online (Sandbox Code Playgroud)

此错误仅发生在生产应用程序中,而不是在开发模式下。

Nga*_*ine 0

Node.js 不知道任何 baseURL。你的浏览器是。因此,在服务器端,您必须提供完整路径,在客户端,当使用相对链接时,它们相对于基本 url,例如https://example.com 作者:Tim Neutkens - Next.js 的合著者和MDX

建议的解决方法之一是full pathgetInitialProps使用 axios 时使用。在你的情况下改变这个:

res = await axiosClient("get").get("/auth/currentuser");
Run Code Online (Sandbox Code Playgroud)

res = await axiosClient("get").get("http://localhost:3000/auth/currentuser"); 
//or use external domian if you not on localhost i.e. https:api.example.com/auth/currentuser
Run Code Online (Sandbox Code Playgroud)

如果这仍然不起作用,请使用 axios API 并按如下方式full path设置:baseUrl

// axios call
await axios({
    method: 'GET',
    url: 'http://abc.herokuapp.com/api/' //or baseURL: 'http://abc.herokuapp.com/api/'
)}
Run Code Online (Sandbox Code Playgroud)

有时间!请阅读本文,它可能会有所帮助:https://github.com/vercel/next.js/issues/5009

更新

您也可以尝试从中构建您的baseURLgetInitialProps context

async getInitialProps({ req }) {
    const protocol = req.headers['x-forwarded-proto'] || 'http'
    const baseUrl = req ? `${protocol}://${req.headers.host}` : ''

    const res = await fetch(baseUrl + '/api/recent/1')
    ...
}
Run Code Online (Sandbox Code Playgroud)