![](/img/trans.png)
[英]Prefetching initial data and refetch if filter is edited using react-query and next.js
[英]404 Not Found Next.js error on React-Query fetch
這是我的情況。 我正在嘗試使用 Express.js 后端設置 Next.js 項目。 根據 Next.js 文檔,我確實將后端設置為常規服務器,而不是自定義服務器。 因此,我不確定將后端設置為常規后端是否已經犯了錯誤。 我正在嘗試使用 axios 從后端端點http://localhost:3500/api/v1/list
獲取數據,並且效果很好。 但是,當我嘗試在第一次加載時實現 React-Query 時,我從后端獲取了正確的數據,但是當它出於某種原因嘗試重新獲取時,它遇到了錯誤的端點http://localhost:3600/api/v1/list
並得到 404 Not Found 錯誤。 看起來它正在將端口從3500
切換到3600
,這是一個前端端口。 在這里,您將找到存儲庫的鏈接,這里是代碼。 如果我做錯了什么,請告訴我,
頁面/sell.js
import axios from 'axios';
import { useQuery } from 'react-query';
export default function SellPage({ response }) {
const { data, isLoading, error } = useQuery('sells', getPosts, {
initialData: response,
});
console.log('data useQuery: ', data);
if (isLoading) return 'Loading...';
if (error) return error.message;
return (
<div>
<p>Hello SellPage!!{data.message}</p>
</div>
);
}
export async function getServerSideProps(context) {
const response = await getPosts();
console.log('response', response);
if (!response) {
return {
notFound: true,
};
}
return {
props: { response }, // will be passed to the page component as props
};
}
async function getPosts() {
console.log('HOST: ', process.env.HOST);
const { data } = await axios.request({
baseURL: process.env.HOST,
url: '/api/v1/list',
method: 'get',
});
return data;
}
_app.js
import React from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
import { ReactQueryDevtools } from 'react-query/devtools';
const queryClient = new QueryClient();
function MyApp({ Component, pageProps }) {
const queryClientRef = React.useRef();
if (!queryClientRef.current) {
queryClientRef.current = new QueryClient();
}
return (
<>
<QueryClientProvider client={queryClientRef.current}>
<Component {...pageProps} />
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
</>
);
}
export default MyApp;
我在您的存儲庫中沒有看到next.config.js
,所以我猜 env 變量沒有捆綁在 js 中,最后您 url 看起來像localhost:
或localhost:undefined
瀏覽器默認為您的客戶端的端口送達。
嘗試添加next.config.js
module.exports = {
env: {
HOST: process.env.HOST,
},
}
參見: https://nextjs.org/docs/api-reference/next.config.js/environment-variables
另一種方法是使用公共運行時變量
module.exports = {
publicRuntimeConfig: {
// Will be available on both server and client
port: 3500,
},
};
// Then
import getConfig from 'next/config';
// Only holds serverRuntimeConfig and publicRuntimeConfig
const { publicRuntimeConfig } = getConfig();
console.log(publicRuntimeConfig.port);
參見: https://nextjs.org/docs/api-reference/next.config.js/runtime-configuration
但請注意,運行時配置會影響優化,最終您可能會得到更大的包,因此您可能想先嘗試構建時間變量。
如果您收到 404,我認為您已訪問服務器但沒有匹配的 API 名稱,因此請嘗試首先在 postman 或類似設備上測試 API,但是如果console.log('HOST: ', process.env.HOST);
打印http://localhost:3600
然后在.env
文件中執行以下操作嘗試將PORT
重命名為SERVER_PORT
或其他
HOSTNAME=localhost
SERVER_PORT=3500
HOST=http://$HOSTNAME:$SERVER_PORT
我不確定,但也許你的前端服務 bash 將PORT
env val 保持為3600
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.