Friday 28 April 2017

NodeJS and React: bundle.js is generated but I get error 404 (failure to load resource)

I have a very basic practice project -- I have some initial content ( a '...' string) and I after the JS environment loads, I want React to take over the div id="root and replace the js content with the react content (a 'hello react' string).

I do an npm run dev and a bundle.js and a bundle.js.map are generated. Then I do an npm start but when I preview the page, only the JS content exists, and upon further inspection, the React script is not even loaded. I receive a 404 failure to load resource error on bundle.js despite the fact the file exists in /public

Here is my webpack.config.js:

module.exports = {
  entry: './src/index.js',
  output: {
    path: __dirname + '/public',
    filename: 'bundle.js'
  },
  module: {
    loaders: [    
  {
    test: /\.json$/,
    loader: 'json-loader'
  },
  {
    test: /\.js$/,
    loader: 'babel-loader'
  }
]
  }

};

Here is my .babelrc:

{
  "presets": ["react", "es2015", "stage-2"]
}

Here is /src/index.js which contains the reactdom.render:

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
    React.createElement('h2', null, 'Hello React'),
    document.getElementById('root')
);

Here is /public/index.ejs:

<%- include('header') -%>

    <div id="root">    
        <%- content -%>
    </div>

<%- include('footer') -%>    

Finally, here is my basic server.js in root directory:

import config from './config';
import apiRouter from './api';

import express from 'express';
const server = express();

server.set('view engine', 'ejs');

server.get('/', (req, res) => {
    res.render('index', {
        content: '...'
    });
});

server.listen(config.port, () => {
  console.log('Express is listening on port ' + config.port);
});    

I have tried searching everywhere for an answer, but haven't had any luck. Any feedback at all is very appreciated! Thank you!



via wilsonsk

No comments:

Post a Comment