react服務端渲染(十)404&&301頁面實現

  1. 服務端發送請求 fetch如何攜帶cookie?
    fetch(url,{
         headers: {
             'Cookie': req.get('Cookie') || ''
         }
    })

    改寫咱們的服務端store,在建立的時候傳入服務端的req參數,再改寫服務端的fetch方法接受req參數git

    export const getServerStore = (req) => {
        return createStore(reducer,applyMiddleware(thunk.withExtraArgument(fetchServer(req))))
    }
  2. 頁面不存在服務端如何返回狀態碼404?
    //服務端代碼
    <Provider store={Store}> <StaticRouter context={context} location={req.path}> { renderRoutes(Routers) } </StaticRouter> </Provider> console.log(context); //404頁面 context.notFound&&res.status(404); //404組件代碼 const NotFound = (props) => { props.staticContext&&(props.staticContext.notFound = true); return (<div>not found</div>) }

    staticRouter提供一個全局的context參數,組件使用props.staticContext能夠獲取這個變量。那麼咱們就能夠經過自定義context的一些變量(notFound)來表明頁面是否匹配到。github

  3. 301頁面如何實現?
    context.action==='REPLACE'&&res.status(301);

    很簡單,staticRouter的context會在咱們頁面重定向以後定義一些變量,其中提供一個action參數,表明是否重定向promise

  4. promise改寫 請求接口錯誤發生時 每一個promise單獨catch錯誤

項目地址:git@github.com:longlongdan/Reactssr.gitcookie

相關文章
相關標籤/搜索