Search code examples
javascriptmean-stackmeanjs

Mean Stack Application: Page does not rerender on refresh, but returns only JSON


I'm currently designing a MEAN.js web application, and for some reason, whenever I refresh the page on a route or window.reload, it does not rerender the page, but only returns the JSON file found at that current route.

For example, when I'm at localhost:8080/people:

If I click here from the main page, I get

Picture of home page

But if I hit refresh or reload the page for whatever reason I get

Picture of result

Does anyone have any idea why this is happening and how to fix it?


Solution

  • Presumably you are using what Angular call's html5Mode routing.

    This uses pushState and friends. These are browser features designed to allow you to build a web app which has what appear to be separate pages with unique, real URLs but when you change the page you actually modify the DOM of the current page (to State B) instead of loading a new one from scratch.

    The design intention for pushState and friends is that if you request the unique, real URL that maps onto State B then the server will provide the browser with the HTML for State B directly.

    This means that:

    • if you arrive on the site without going to the homepage first, then you load the content you are trying to load directly (which is faster than loading the homepage and then modifying it with JavaScript).
    • if you arrive on the site without JavaScript working (which could be for many reasons, then everything still works. See also Progressive Enhancement and Unobtrusive JavaScript.

    What you've done wrong is that your URLs are mapping onto your JSON based API instead of server side processes that generate the pages.

    You need to write the server side processes. You could consider using the Accept header to allow them to share URLs with the API (so the server returns either JSON or HTML depending on what the client says it accepts).