Fix notfound status code in server rendering

This commit is contained in:
Kimmo Puputti 2017-02-16 12:37:14 +02:00
parent 28da28cf05
commit 2863f9dbef
4 changed files with 43 additions and 16 deletions

View file

@ -151,7 +151,12 @@ app.get('*', (req, res) => {
const html = render(req.url, context, preloadedState);
if (context.url) {
// React Router injects the context.url if a redirect was rendered
res.redirect(context.url);
} else if (context.notfound) {
// NotFoundPage component injects the context.notfound when a
// 404 should be returned
res.status(404).send(html);
} else {
res.send(html);
}

View file

@ -1,9 +1,31 @@
import React from 'react';
import { Link } from 'react-router-dom';
import { PageLayout } from '../../components';
import React, { Component, PropTypes } from 'react';
import { withRouter } from 'react-router-dom';
import { PageLayout, NamedLink } from '../../components';
export default () => (
<PageLayout title="Page not found">
<Link to="/">Index page</Link>
</PageLayout>
);
export class NotFoundPageComponent extends Component {
componentWillMount() {
// The StaticRouter component used in server side rendering
// provides the context object. We attach a `notfound` flag to
// the context to tell the server to change the response status
// code into a 404.
this.props.staticContext.notfound = true;
}
render() {
return (
<PageLayout title="Page not found">
<NamedLink name="LandingPage">Home</NamedLink>
</PageLayout>
);
}
}
NotFoundPageComponent.defaultProps = { staticContext: {} };
const { object } = PropTypes;
NotFoundPageComponent.propTypes = {
// context object from StaticRouter, injected by the withRouter wrapper
staticContext: object,
};
export default withRouter(NotFoundPageComponent);

View file

@ -1,10 +1,11 @@
import React from 'react';
import { renderShallow } from '../../util/test-helpers';
import NotFoundPage from './NotFoundPage';
import { StaticRouter } from 'react-router-dom';
import { renderShallow, renderDeep } from '../../util/test-helpers';
import { NotFoundPageComponent } from './NotFoundPage';
describe('NotFoundPage', () => {
it('matches snapshot', () => {
const tree = renderShallow(<NotFoundPage />);
const tree = renderShallow(<NotFoundPageComponent />);
expect(tree).toMatchSnapshot();
});
});

View file

@ -1,10 +1,9 @@
exports[`NotFoundPage matches snapshot 1`] = `
<Connect(withRouter(PageLayout))
title="Page not found">
<Link
replace={false}
to="/">
Index page
</Link>
<withFlattenedRoutes(NamedLink)
name="LandingPage">
Home
</withFlattenedRoutes(NamedLink)>
</Connect(withRouter(PageLayout))>
`;