我使用next js时,试图调用一个APIendpoint(调度一个redux动作)在getFronalProps.我得到404错误,我的 /api/被代理在nginx服务器,所有其他路由工作得很好,只有这个路由导致的问题。
我已经尝试将api fetch函数调用更改为async,但仍然是相同的错误。
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;
}
错误响应错误:在IncomingMessage. handleStreamEnd(/home/ubuntu/main WebApp/node_modules/axios/lib/core/createError.js:16:15)在结算(/home/ubuntu/main WebApp/node_modules/axios/lib/core/settle.js:18:12)在IncomingMessage.handleStreamEnd(/home/ubuntu/main WebApp/node_modules/axios/lib/适配器/http.js:202:11)在IncomingMessage.emit(events.js:198:15)在endReadableNT(_stream_readable.js:1139:12)在process TicksAndRejtions(内部/进程/task_queues.js:81:17)请求失败,状态代码为404
所以问题是getNovalProps在服务器中执行,axios不能运行服务器,而是使用https://www.npmjs.com/package/isomorphic-fetch。