Thursday 1 June 2017

React-Router does not return 404 when data not found on the same path

I'm using a Universal React Library But some features I changed. For example I don't use Api proxy

I have a Route for routing for example

request: /some-title/ have to go Content Component.

request: /kdjfklasjd/ have to go NotFound with 404 status.

    const isContent = (state, cb) => {
    if (!seoLoaded(store.getState())) {
      store.dispatch(getUrl(state.location.pathname)).then(() =>{
        if (is404(store.getState())) {
          cb(null, NotFound);
        } else {
          cb(null, Content);
        }
      });
    }
   };
return( 
<Route>
      <Route path="/" component={App} history={browserHistory}>
        { /* Home (main) route */ }
        <IndexRoute component={Home}/>
        <Route onEnter={checkRedirect}>
          <Route path="/*" getComponent={isContent} />
        </Route>
      </Route>
      { /* Catch all route */ }
      <Route path="*" component={NotFound} status={404}/>
    </Route>
);

I tried NestedStatus but It does not work regular. Sometimes It have to response 200 status but It returns 404.

from server.js

  match({
    history,
    routes: (isMobile ? mobile(store) : desktop(store)),
    location: req.originalUrl
  }, (error, redirectLocation, renderProps) => {
    const is404 = renderProps.routes.find(r => r.status === 404) !== undefined;
    if (redirectLocation) {
      res.redirect(301, redirectLocation.pathname + redirectLocation.search);
    } else if (error) {
      console.error('ROUTER ERROR:', pretty.render(error));
      res.status(500);
      hydrateOnClient();
    } else if (renderProps) {
      loadOnServer({...renderProps, store, helpers: {client}}).then(() => {
        const component = (
          <Provider store={store} key="provider">
            <ReduxAsyncConnect {...renderProps} />
          </Provider>
        );
        console.log(is404);
        if(is404) {
          res.status(404);
        }
        console.log('server2', nStatus);

        global.navigator = {userAgent: req.headers['user-agent']};

        res.send('<!doctype html>\n' +
          ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={component}
                                        store={store} isMobile={isMobile}/>));
      });
    } else {
      res.status(404).send('Not found');
    }
  });
});



via Mustafa Dilaver

No comments:

Post a Comment