前言
github: https://github.com/code-coder...
已經用Next.js快兩個月了,項目已經提測了,這裏總結一下開發過程中,以及在部署的時候遇到一些棘手的問題。
疑難雜症
1. 移動端overflow:auto,ios滾動卡頓
解決方案: 主容器增加樣式-webkit-overflow-scrolling: touch;
2. dev mode路由跳轉後樣式丟失
原因:dev下樣式根據頁面動態加載,瀏覽器緩存文件styles.chunk.css
造成樣式不更新。
解決方案: 利用版本號強制重載樣式文件
示例1:
// 在Layout組件中
<Head>
<title>{title}</title>
{process.env.NODE_ENV !== 'production' && (<link rel="stylesheet" type="text/css" href={'/_next/static/css/styles.chunk.css?v=' + Router.route} />)}
</Head>
示例2:
// 在_app.js中
import Router from 'next/router';
Router.events.on('routeChangeComplete', () => {
if (process.env.NODE_ENV !== 'production') {
const els = document.querySelectorAll('link[href*="/_next/static/css/styles.chunk.css"]');
const timestamp = new Date().valueOf();
els[0].href = '/_next/static/css/styles.chunk.css?v=' + timestamp;
}
});
3、Android 鍵盤彈起窗口會變小,有 flex 或者 position 是 absolute 或者 fixed 佈局會變
這裏直接把body.height
設置爲瀏覽器的窗口高度。
doc.body.style.height = docEl.clientHeight + 'px';
4、跨域及傳遞cookie的問題
第一步,登錄成功後api服務器返回cookie。
跨域訪問要接收cookie,解決辦法也很簡單只需要API服務器根據請求地址設置Access-Control-Allow-Origin
的值爲請求地址的ip就可以了(測試環境可以動態設置這個ip,生產可以設置指定的域名或者ip地址)。
第二步,瀏覽器自動緩存,再後續請求中攜帶此cookie。
fetch或axois請求都默認不帶cookie,需要通過option配置打開。
- fetch要配置`{ credentials: 'include', mode: 'cors' }`
- axois要配置`axios.defaults.withCredentials=true;`
另外,還可以通過服務器代理走內網訪問api。
以下爲我們公司所採用的解決方案:
爲了解決跨域以及部署不同服務器需要修改 api 地址的問題,我們使用 前端服務器代理 + dns 解析。整個流程如下圖所示:
通過NODE_ENV
環境變量來配置開發和生產的地址。
const isProd = process.env.NODE_ENV === 'production';
process.env.BACKEND_URL = isProd ? '/relative_url' : 'http://text.api.com';
process.env.BACKEND_URL_SERVER_SIDE = isProd ? 'http://bff.api.com' : 'https://prod.api.com';
module.exports = {
'process.env.BACKEND_URL': process.env.BACKEND_URL, // 客戶端渲染請求,是個相對地址,在前端服務器被代理到API服務器
'process.env.BACKEND_URL_SERVER_SIDE': process.env.BACKEND_URL_SERVER_SIDE // 服務端渲染請求,是API服務器地址,僅供內網訪問
};
5、服務端渲染時帶 cookie 請求的問題
這裏用到一個插件叫nookies。
在_app.js
中全局解析cookies注入ctx
:
static async getInitialProps({ Component, ctx }) {
let pageProps = {};
let cookies = {};
if (ctx.isServer) {
cookies = parseCookies(ctx);
}
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps({ ctx, cookies });
}
return { pageProps };
}
然後就可以通過頁面請求:
static async getInitialProps({ ctx }) {
const { store, req, isServer, cookies } = ctx;
store.dispatch(setNav({ navTitle: 'Home', isHome: true }));
store.dispatch(getDataStart({ settings: { isServer, cookies } }));
}
在proxyFetch
中就會根據isServer
的值來分辨是服務端API請求還是客戶端API請求。服務端請求會把cookies寫入Fetch的header中。
const prefix = isServer ? process.env.BACKEND_URL_SERVER_SIDE : process.env.BACKEND_URL;
isServer && (this.headers['cookie'] = 'EGG_SESS=' + cookies['EGG_SESS'] + ';';)
// fetch核心
fetch(prefix + url, { headers: this.headers, ...this.init, ...options })