Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js Server Side Rendering - Request '/json/version/

I've got an express server running to pre-render my react application. I've got a routes file that matches the HomeContainer to the base route / and all other routes match to page not found.

import HomeContainer from 'containers/home-container/home-container';
import PageNotFound from 'components/page-not-found/page-not-found';

const routes = [
  {
    path: '/',
    exact: true,
    component: HomeContainer
  },
  {
    path: '*',
    component: PageNotFound
  }
];

export default routes;

The problem I'm having is when I run the application on the server the page not found route gets rendered before quickly changing to the HomeContainer route.

I've identified that this is occurring because my express server is making a request to /json/version before it makes a request to /, this route doesn't match one in my routes file and therefore the page not found component is rendered.

Now what I don't get is why it's making this request and how to stop the page not found component being rendered before the home container. I've tried debugging the node server and the earliest place I can find this path being referenced is in an emit call inside a file called _http_server.js

Below is a screenshot of the debugger and where I found the URL being referenced.

Debugger Screenshot

Also for reference, I've included my express server below.

import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { Provider } from 'react-redux';
import { StaticRouter, matchPath } from 'react-router-dom';
import serialize from 'serialize-javascript';
import expressStaticGzip from 'express-static-gzip';
import sourceMapSupport from 'source-map-support';

import routes from 'routes';
import configureStore from 'store';
import AppContainer from 'containers/app-container/app-container';

if (process.env.NODE_ENV === 'development') {
  sourceMapSupport.install();
}

const app = express();

app.use(expressStaticGzip('./static/assets'));

app.get('*', (req, res, next) => {
  const store = configureStore();

  /**
   * Load initial data into state
   * match requested URL path to the component in routes
   * check for 'fireInitialActions' method (found in the container components)
   * and dispatch if it exists
   */
  const routeComponentPromises = routes.reduce((accumulator, route) => {
    if (matchPath(req.url, route) && route.component && route.component.fireInitialActions) {
      accumulator.push(Promise.resolve(store.dispatch(route.component.fireInitialActions())));
    }

    return accumulator;
  }, []);

  Promise.all(routeComponentPromises)
    .then(() => {
      const context = {};
      const markup = renderToString(
        <Provider store={store}>
          <StaticRouter location={req.url} context={context}>
            <AppContainer />
          </StaticRouter>
        </Provider>
      );

      const initialData = store.getState();
      res.send(`
        <!DOCTYPE html>
        <html>
          <head>
            <title>Test</title>
            <script src='vendor.js' defer></script>
            <script src='app.js' defer></script>
            <script>window.__initialData__ = ${serialize(initialData)}</script>
          </head>
          <body>
            <div id="root">${markup}</div>
          </body>
        </html>
      `);
    })
    .catch(next);
});

app.listen(process.env.PORT || 3000, () => {
  console.log('Server is listening');
});

Does anyone know why is this happening and how I can solve my problem?

EDIT: Here's a video showing the issue - https://d26dzxoao6i3hh.cloudfront.net/items/2z3y3f1x3N1D2e422W42/Screen%20Recording%202017-10-23%20at%2012.24%20pm.mov

like image 397
woolm110 Avatar asked Oct 23 '17 11:10

woolm110


People also ask

How do I find JSON version?

To check which version of json is installed, use pip show json or pip3 show json in your Linux terminal.

What content-type is sent in the HTTP response when Res JSON () produces the response?

The res. json function on the other handsets the content-type header to application/JSON so that the client treats the response string as a valid JSON object. It also then returns the response to the client.

What is Express JSON ()?

json() is a built-in middleware function in Express. This method is used to parse the incoming requests with JSON payloads and is based upon the bodyparser. This method returns the middleware that only parses JSON and only looks at the requests where the content-type header matches the type option.

How do I return a JSON response in node JS?

We need to require an express module before using it, and we can do that by adding the code given below at the top of our server code. const express = require('express'); const app = express(); Step 4(Using express to return JSON data): Now our express is completely ready to use.


1 Answers

I faced the same problem right after I had run my node application with --inspect key. These strange GET requests to /json and /json/version were sent by chrome inspector.

So, the solution (in my case) is:

  1. Go to chrome://inspect.
  2. Click the link "Open dedicated DevTools for Node";
  3. Open Connection tab.
  4. Remove your endpoint from the list.
like image 86
Kirill Murashkin Avatar answered Oct 04 '22 09:10

Kirill Murashkin