如何修复 axios Next js 中的“错误:请求失败,状态代码 404”

Abh*_*bhi 5 javascript nginx reactjs axios next.js

当尝试在 getInitialProps 中调用 API 端点(调度 redux 操作)时,我正在使用 next js。我收到 404 错误,我的 /api/ 在 nginx 服务器中被代理,所有其他路由都工作得很好,只有这个路由导致了问题。

我尝试将 api fetch 函数调用更改为异步,但仍然出现相同的错误。

static async getInitialProps({ store, query: { id } }) {
    await store.dispatch(fetchP(id));
    console.log('GetIntial');
    return { id };
 }
Run Code Online (Sandbox Code Playgroud)

我的动作创造者

export const fetchp = id => async dispatch => {
  dispatch({ type: FETCH_P_DETAILS_STARTED });
  await API.get(`ps/${id}`)
    .then(res => {
      console.log(res);
      dispatch({
        type: FETCH_P_DETAILS_SUCCESS,
        payload: res.data.data,
      });
    })
    .catch(err => {
      console.log(err);
      if (!err.response) {
        // network error
        err.message = 'Error: Network Error';
        console.log(err.message);
      } else if (err.code === 'ECONNABORTED') {
        console.log('Timeout');
      } else {
        err.message = err.message;
      }
      dispatch({
        type: FETCH_P_DETAILS_FAILURE,
        payload: err.message,
      });
    });
};
Run Code Online (Sandbox Code Playgroud)

我的 nginx 配置

  location /api/ {
    proxy_pass http://127.0.0.1:5000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
  }
Run Code Online (Sandbox Code Playgroud)

错误响应错误:在解决(/home/ubuntu/mainWebApp/node_modules/axios/)处的createError(/home/ubuntu/mainWebApp/node_modules/axios/lib/core/createError.js:16:15)请求失败,状态代码为404 lib/core/settle.js:18:12) 在 IncomingMessage.handleStreamEnd (/home/ubuntu/mainWebApp/node_modules/axios/lib/adapters/http.js:202:11) 在 IncomingMessage.emit (events.js:198) :15) 在 endReadableNT (_stream_readable.js:1139:12) 在 processTicksAndRejections (internal/process/task_queues.js:81:17)

evg*_*tia 5

所以问题是 getInitialProps 在服务器中执行,而 axios 无法运行服务器,请使用https://www.npmjs.com/package/isomorphic-fetch代替。