【问题标题】:How to fix, "Error: Request failed with status code 404" in axios Next js如何修复 axios Next js 中的“错误:请求失败,状态码为 404”
【发布时间】:2019-11-05 09:07:54
【问题描述】:

我在尝试调用 API 端点时使用下一个 js(调度一个 redux 操作)在 getInitialProps 中。我收到 404 错误,我的 /api/ 在 nginx 服务器中代理,所有其他路由都运行良好,只有这个 路线导致问题。

我尝试将 api fetch 函数调用更改为异步,但是 还是一样的错误。

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

我的动作创建者

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,
      });
    });
};

我的 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;
  }

错误响应错误:请求失败,状态码 404 在 createError (/home/ubuntu/mainWebApp/node_modules/axios/lib/core/createError.js:16:15) 在解决(/home/ubuntu/mainWebApp/node_modules/axios/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)

【问题讨论】:

  • console.log(id)getInitialProps 内部返回了什么
  • @evgeni fotia 它打印正确的 id 值

标签: javascript reactjs nginx axios next.js


【解决方案1】:

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

【讨论】:

  • 我尝试在 getIntialProps 中使用 console.log(id) 但它没有登录控制台,我认为 getInitialprops 没有执行。
  • @AbhiKanimilli 试试console.log('Heloooooooooooo'),因为如果getIntialProps 没有被执行,你说的就没有意义了,就没有请求
  • 等待 store.dispatch(fetchPg(id)); console.log('Heloooooooooooo'); console.log(id);
  • 如果我在发送后登录,它不会登录
  • @AbhiKanimilli 这很正常。重要的是它在await API.get(ps/${id}) 之前记录id。所以只要把 axios 改成上面的包就行了
猜你喜欢
  • 1970-01-01
  • 2019-08-15
  • 2021-04-25
  • 2022-11-13
  • 2021-04-10
  • 2020-04-05
  • 2020-09-18
  • 2019-10-12
  • 1970-01-01
相关资源
最近更新 更多