MERN Stack: The Complete Guide Step by Step

67
252
mern stack tutorial

The MERN Stack Tutorial is a basic CRUD application in which React.js consumes the frontend, Node.js as a server platform, the Express web framework of Node.js, and MongoDB as a NoSQL database.

MERN Stack

MERN stands for MongoDB, Express, React.js, and Node.js. React.js is a very famous UI library provided by Facebook.

We are using Express web framework, which gives us Routing functionality to our application and Middlewares through which we can filter our HTTP requests.

First, we must build the front end using React.js, set up routing, and create a basic form. After that, we build the backend using the express framework.

Step 1: Draft ReactJS Application.

To set up react application at the front end, we use the create-react-app starter kit to initialize our application, so go to the terminal. If you are a Windows user, please open CMD in Administrator mode and type the following.

npm install -g create-react-app

If you are MAC or Linux user, please type the following command.

sudo npm install -g create-react-app

Go to your project directory and type the following command

create-react-app react-frontend

I have given our project’s name react-frontend; you can share whatever you want. It will take some time to initialize our app, and it also installs project dependencies.

After that, go into the project folder. In my case, it is react-frontend. Type the following command.

npm start

At http://localhost:3000/

The development server is started, and the basic boilerplate will show in the browser.

MERN Stack Tutorial

Step 2: Install React and ReactDOM.

We need to set up the react-router-dom package. It provides us with client-side routing for our web application. So download this package via npm.

npm install --save react-router-dom

Note:  I am using React Router version 4.1.1, which is new from the previous version of the routing package and is based on components.

I am providing you my package.json file, so you do not have to worry about it, and if you have any problem, please check out all the dependency versions with mine.

{
  "name": "react-frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "react-router-dom": "^4.1.1",
    "react-scripts": "0.9.5"
  },
  "devDependencies": {},
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

Now define your routes in an index.js file in the src directory.

// index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';

import App from './App';

ReactDOM.render(
  <Router>
      <div>
        <Route exact path='/' component={App} />
      </div>
  </Router>,
  document.getElementById('root')
);

I am using an ES6 version of JavaScript, importing all the modules from downloaded packages. Here  I am rendering routes as components. Until now, I have defined only one app route: our app route.

Step 3: Make a components folder.

Create one directory in src called components.

In that, create one component called AddItem.js.

// AddItem.js

import React, { Component } from 'react';

class AddItem extends Component {
  render() {
    return (
        <div>
          <h2>Welcome to Add Item</h2>
        </div>
    );
  }
}

export default AddItem;

We need to import this component to the index.js file and register a route for this component.

// index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';

import App from './App';
import AddItem from './components/AddItem';

ReactDOM.render(
  <Router>
      <div>
        <Route exact path='/' component={App} />
        <Route path='/add-item' component={AddItem} />
      </div>
  </Router>,
  document.getElementById('root')
);

Now, go to this URL: http://localhost:3000/add-item

You will see “Welcome to Add Item.”

Now, go to this URL: http://localhost:3000.

You will see “Welcome to React.”

Possible Errors:

A <Router> may have only one child element

Possible Solutions:

// index.js 

<Router>
      <div>
        <Route exact path='/' component={App} />
        <Route path='/add-item' component={AddItem} />
      </div>
  </Router>

Wrap <div> tag around the Route component, and It will solve this issue.

Step 4: Create a form.

Add the Bootstrap CSS framework to our application. So copy the CDN from an official bootstrap website and put it into the index.html file.

<!-- index.html -->

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Now, add the bootstrap classes to our add-item.js page

Possible Errors:

Unknown DOM property class.

Possible Solutions:

Use the className property instead of class in React application.

Create a form to submit the item to the server.

// AddItem.js

import React, { Component } from 'react';

class AddItem extends Component {

  constructor(props) {
      super(props);
      this.state = {value: ''};

      this.handleChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event) {
      this.setState({value: event.target.value});
    }

    handleSubmit(event) {
      alert(this.state.value);
      event.preventDefault();
    }

    render() {
      return (
        <div className="container">
          <form onSubmit={this.handleSubmit}>
            <label>
              Add Item:
              <input type="text" value={this.state.value} onChange={this.handleChange} className="form-control"/>
            </label><br/>
            <input type="submit" value="Submit" className="btn btn-primary"/>
          </form>
      </div>
      );
    }
  }

export default AddItem;

I have used ES6 class syntax. React is all about state change, so first, I have set the state to null, and then when the user starts typing in the text box, the state is changed dynamically.

The user puts whatever value in it, and the state also changes and sets the matter according to it. 

After the user submits the form, the state value, which is set, is sent to the server. 

So, now we need to send that value to our Node.js server. 

I am using one AJAX request library called Axios, which is only used for AJAX requests to the server.

Step 5: Make the ItemService.js file.

Create a service file in the components folder for Items called ItemService.js and put the following code in it.

// ItemService.js

import axios from 'axios';

class ItemService {

  sendData(data) {
    axios.post('http://localhost:4200/items/add/post', {
    item: data
  })
  .then(function (response) {
      console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  }
}

export default ItemService;

Here, I am using the axios library, so I have sent the post request to the server, which is the express node server.

Now we need to import this file into our AddItem.js file.

// AddItem.js

import React, { Component } from 'react';
import ItemService from './ItemService';

class AddItem extends Component {

  constructor(props) {
      super(props);
      this.state = {value: ''};
      this.addItemService = new ItemService();

      this.handleChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event) {
      this.setState({value: event.target.value});
    }

    handleSubmit(event) {
      event.preventDefault();
      this.addItemService.sendData(this.state.value);
      this.props.history.push('/');
    }

    render() {
      return (
        <div className="container">
          <form onSubmit={this.handleSubmit}>
            <label>
              Add Item:
              <input type="text" value={this.state.value} onChange={this.handleChange} className="form-control"/>
            </label><br/>
            <input type="submit" value="Submit" className="btn btn-primary"/>
          </form>
      </div>
      );
    }
  }

export default AddItem;

Created the object of ItemService class and called its sendData method. Then, pass the input value as a parameter, and be ready to go.

Step 6: Make a nodejs express project.

We need to create a backend for our application, so I am using node.js and express web framework.

Create a project folder, go to that directory, and put the following command in your terminal.

npm init

After answering all the data, your root folder package.json file will be created. This file is configurable for our dependencies, so when we download new packages from Node Package Manager, the package.json file will automatically update.

Step 7: Install the expressjs framework.

Get the Express package from Node Package Manager by typing the following command on the terminal.

npm install --save express

Possible Error Info: npm WARN install Refusing to install express as a dependency of itself

If you find the above error during installation, make sure your project name must not contain the “express” word.

Step 8: Make an app.js file.

Create a file in root called “app.js.” This is our main server file which bootstraps the node server and serves some static files. For example, please put the following code in it.

// app.js

var express = require('express');
var app = express();
var port = 4200;
app.listen(port, function(){
  console.log('hello world');
})

Now go to the terminal, and if you type node app, you will get hello world in a console.

If we do not want to restart the server manually, we can use one package called nodemon. It is the kind of server that reloads whenever we change the file.

npm install -g nodemon

Change the package.json file and add the following line in the “scripts” object.

"start": "nodemon app.js"

When you type in the terminal “npm start,” it will bootstrap the server, and when we change the files, it will automatically restart.

Switch to chrome and hit: http://localhost:4200. We get “Hello Express” in the browser.

Step 9: Install CORS Middleware.

Create Mongoose database connection and also use CORS middleware to request cross-origin domain. Here we are using CORS middleware to bypass the security.

// app.js

var express = require('express');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var port = 4200;
var cors = require('cors');

// Mongoose connection with mongodb
mongoose.Promise = require('bluebird');
mongoose.connect('mongodb://<uname>:<pwd>@ds139322.mlab.com:39322/aufinancex')
    .then(() => { // if all is ok we will be here
      console.log('Start');
    })
    .catch(err => { // if error we will be here
        console.error('App starting error:', err.stack);
        process.exit(1);
    });

// Required application specific custom router module
var itemRouter = require('./src/routes/itemRouter');

// Use middlewares to set view engine and post json data to the server
app.use(express.static('public'));
app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.use('/items', itemRouter);

// Start the server
app.listen(port, function(){
  console.log('Server is running on Port: ',port);
});

Step 10: Make routes for our application.

Now, create an itemRouter.js file in the src >> routes directory.

I have coded all the CRUD functionality at the backend, so don’t worry about it.

I have used the Mongoose model to insert, get, update and delete the data.

// itemRoutes.js

var express = require('express');
var app = express();
var itemRouter = express.Router();

// Require Item model in our routes module
var Item = require('../models/Item');

// Defined store route
itemRouter.route('/add/post').post(function (req, res) {
  var item = new Item(req.body);
      item.save()
    .then(item => {
    res.json('Item added successfully');
    })
    .catch(err => {
    res.status(400).send("unable to save to database");
    });
});

// Defined get data(index or listing) route
itemRouter.route('/').get(function (req, res) {
  Item.find(function (err, itms){
    if(err){
      console.log(err);
    }
    else {
      res.json(itms);
    }
  });
});

// Defined edit route
itemRouter.route('/edit/:id').get(function (req, res) {
  var id = req.params.id;
  Item.findById(id, function (err, item){
      res.json(item);
  });
});

//  Defined update route
itemRouter.route('/update/:id').post(function (req, res) {
  Item.findById(req.params.id, function(err, item) {
    if (!item)
      return next(new Error('Could not load Document'));
    else {
      // do your updates here
      item.item = req.body.item;

      item.save().then(item => {
          res.json('Update complete');
      })
      .catch(err => {
            res.status(400).send("unable to update the database");
      });
    }
  });
});

// Defined delete | remove | destroy route
itemRouter.route('/delete/:id').get(function (req, res) {
  Item.findByIdAndRemove({_id: req.params.id},
	   function(err, item){
		if(err) res.json(err);
		else res.json('Successfully removed');
	});
});

module.exports = itemRouter;

Step 11: Create a mongoose schema.

Create a model for Mongoose Schema. For example, create a new directory in the src folder called models and then make another file called Item.js.

// Item.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// Define collection and schema for Items
var Item = new Schema({
  item: {
    type: String
  },

},{
	collection: 'items'
});

module.exports = mongoose.model('Item', Item);

Possible Errors:

XMLHttpRequest cannot load http://localhost:4200/items/add/post. Response to a preflight request does not pass the access control check: No ‘Access-Control-Allow-Origin’ header is on the requested resource. Origin ‘http://localhost:3000’ is therefore not allowed access.

Possible Solutions:

Use a middleware package called ‘cors‘ in the express application

npm install --save cors

Please include this in the app.js file in the node.js Express project and add it as a middleware

//app.js

var cors = require('cors');

app.use(cors());

Now, switch to the URL: http://localhost:3000/add-item

You can see one form but the item name, and if your backend database connection is excellent, you can insert the data into the mongo database and redirect it back to your home router.

Step 12: Register the routes at the front end.

We need to register the index route to list the items.

//index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';

import App from './App';
import AddItem from './components/AddItem';
import IndexItem from './components/IndexItem';

ReactDOM.render(
  <Router>
      <div>
        <Route exact path='/' component={App} />
        <Route path='/add-item' component={AddItem} />
        <Route path='/index' component={IndexItem} />
      </div>
  </Router>,
  document.getElementById('root')
);

Create a new file in components called IndexItem.js

// IndexItem.js

import React, { Component } from 'react';
import ItemService from './ItemService';
import axios from 'axios';
import TableRow from './TableRow';

class IndexItem extends Component {

  constructor(props) {
      super(props);
      this.state = {value: '', items: ''};
      this.addItemService = new ItemService();
    }
    componentDidMount(){
      axios.get('http://localhost:4200/items')
      .then(response => {
        this.setState({ items: response.data });
      })
      .catch(function (error) {
        console.log(error);
      })
    }
    tabRow(){
      if(this.state.items instanceof Array){
        return this.state.items.map(function(object, i){
            return <TableRow obj={object} key={i} />;
        })
      }
    }

    render() {
      return (
        <div className="container">
            <table className="table table-striped">
              <thead>
                <tr>
                  <td>No.</td>
                  <td>Item</td>
                </tr>
              </thead>
              <tbody>
                {this.tabRow()}
              </tbody>
            </table>
        </div>
      );
    }
  }

export default IndexItem;

Here, I have sent the axios to get a request to the node.js server, and in response, we are getting the data.

So we are rendering that data in our ItemIndex.js file and creating one more component, which is only responsible for making the table.

To create one more component called TableRow.js

// TableRow.js

import React, { Component } from 'react';

class TableRow extends Component {
  render() {
    return (
        <tr>
          <td>
            {this.props.obj._id}
          </td>
          <td>
            {this.props.obj.item}
          </td>
          <td>
            <button className="btn btn-primary">Edit</button>
          </td>
          <td>
            <button className="btn btn-danger">Delete</button>
          </td>
        </tr>
    );
  }
}

export default TableRow;

So Indexing of data is complete till now.

Now, the remaining is editing and deleting.

Step 13: Make an editItem.js file.

Create a new edit file in components called “EditItem.js.” Please put the following code in it.

// EditItem.js

import React, { Component } from 'react';
import axios from 'axios';

class EditItem extends Component {

  constructor(props) {
      super(props);
      this.state = {items: ''};
  }

  componentDidMount(){
    axios.get('http://localhost:4200/items/edit/'+this.props.match.params.id)
    .then(response => {
      this.setState({ items: response.data });
    })
    .catch(function (error) {
      console.log(error);
    })
  }

  render() {
    return (
          <div className="container">
            <form onSubmit={this.handleSubmit}>
              <label>
                Edit Item:
                <input type="text" value={this.state.items.item}  className="form-control"/>
              </label><br/>
              <input type="submit" value="Update" className="btn btn-primary"/>
            </form>
        </div>
    );
  }
}

export default EditItem;

Here I am fetching exact editable data from the database via their  _id

Also, put an edit link in the TableRow.js file.

// TableRow.js

<Link to={"/edit/"+this.props.obj._id} className="btn btn-primary">Edit</Link>

Register the route in the index.js file.

// Index.js

import EditItem from './components/EditItem';
<Route path='/edit/:id' component={EditItem} />

Step 14: Update the data.

Updating our data, so we need to change the EditItem.js file

// EditItem.js

import React, { Component } from 'react';
import axios from 'axios';
import ItemService from './ItemService';

class EditItem extends Component {

  constructor(props) {
      super(props);
      this.addItemService = new ItemService();
      this.handleChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
      this.state = {value: '' };
  }

  componentDidMount(){
    axios.get('http://localhost:4200/items/edit/'+this.props.match.params.id)
    .then(response => {
      this.setState({ value: response.data});
    })
    .catch(function (error) {
      console.log(error);
    })
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    event.preventDefault();
    this.addItemService.updateData(this.state.value,this.props.match.params.id);
    this.props.history.push('/index');
  }

  render() {
    return (
          <div className="container">
            <form onSubmit={this.handleSubmit}>
              <label>
                Edit Item:
                <input type="text" value={this.state.value.item} onChange={this.handleChange}  className="form-control"/>
              </label><br/>
              <input type="submit" value="Update" className="btn btn-primary"/>
            </form>
        </div>
    );
  }
}

export default EditItem;

We need to code the update function in the ItemService.js file

// ItemService.js

  updateData(data, id){
    axios.post('http://localhost:4200/items/update/'+id, {
      item: data
    })
    .then(res => this.setState({ items: res.data }))
    .catch(err => console.log(err))
  }

When you edit the file and update the data, you will redirect the index.js component, and when you refresh the page, the data will be updated.

Step 15: Delete the data.

We proceed to delete the data. So, we need to modify the TableRow.js file, where we have put the delete button.

// TableRow.js

import React, { Component } from 'react';
import {Link} from 'react-router-dom';
import ItemService from './ItemService';

class TableRow extends Component {

  constructor(props) {
      super(props);
      this.addItemService = new ItemService();
      this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    event.preventDefault();
    this.addItemService.deleteData(this.props.obj._id);
  }
  render() {
    return (
        <tr>
          <td>
            {this.props.obj._id}
          </td>
          <td>
            {this.props.obj.item}
          </td>
          <td>
          <Link to={"/edit/"+this.props.obj._id} className="btn btn-primary">Edit</Link>
        </td>
          <td>
            <form onSubmit={this.handleSubmit}>
              <input type="submit" value="Delete" className="btn btn-danger"/>
            </form>
          </td>
        </tr>
    );
  }
}

export default TableRow;

The next step is to code the ItemService.js file.

// ItemService.js

deleteData(id){
    axios.get('http://localhost:4200/items/delete/'+id)
    .then(console.log('Deleted').catch(err => console.log(err))
  }

When you delete the button and refresh the page, we can see that the item has been removed.

MERN Stack Tutorial

Note: In the React.js project, generally, page refresh is not worth it, but I have created this project to showcase how we can work with both React.js and Node.js

GitHub Links

  1. React.js Project
  2. Node.js Express Project

GitHub Steps to Use  MERN Stack

  1. Clone The reactfrontend project repo.
  2. Go to the project folder
  3. and run the command “npm install” in your terminal
  4. after that, run the command “npm start.”
  5. Clone the expressbackend repo.
  6. Go to the project folder
  7. run the command “npm install” in your terminal
  8. In the app.js file, change MongoDB URI to your particular URI
  9. Run the command “npm start.
  10. Now, go to this URL: http://localhost:3000/add-item.

That’s it.

67 Comments

  1. I’m half way through this and it is fantastic.

    It’s the first MERN tutorial that I have actually got to work (so far so good anyway).

  2. In Step 3, one typing mistake filename should be AddItem.js in 2nd line (In that create one component called AppItem.js)

  3. So can you explain why the tutorial has all the files, front-end and back-end in one project. But then in your git-hub you separated them into two projects?

  4. When I run your “Github Steps To Use MERN Stack Tutorial” setps I get this error running the frontend. The backend started up fine:

    > react-frontend@0.1.0 start /home/cabox/workspace/reactfrontend
    > react-scripts start

    sh: 1: react-scripts: not found

    npm ERR! Linux 2.6.32-042stab112.15
    npm ERR! argv “/usr/bin/nodejs” “/usr/bin/npm” “start”
    npm ERR! node v6.11.1
    npm ERR! npm v3.10.10
    npm ERR! file sh
    npm ERR! code ELIFECYCLE
    npm ERR! errno ENOENT
    npm ERR! syscall spawn
    npm ERR! react-frontend@0.1.0 start: `react-scripts start`
    npm ERR! spawn ENOENT
    npm ERR!
    npm ERR! Failed at the react-frontend@0.1.0 start script ‘react-scripts start’.
    npm ERR! Make sure you have the latest version of node.js and npm installed.
    npm ERR! If you do, this is most likely a problem with the react-frontend package,
    npm ERR! not with npm itself.
    npm ERR! Tell the author that this fails on your system:
    npm ERR! react-scripts start
    npm ERR! You can get information on how to open an issue for this project with:
    npm ERR! npm bugs react-frontend
    npm ERR! Or if that isn’t available, you can get their info via:
    npm ERR! npm owner ls react-frontend
    npm ERR! There is likely additional logging output above.

    npm ERR! Please include the following file with any support request:
    npm ERR! /home/cabox/workspace/reactfrontend/npm-debug.log
    x-codeanywhere:~/workspace/reactfrontend$ npm list react react-dom react-router-dom react-scripts
    react-frontend@0.1.0 /home/cabox/workspace/reactfrontend
    +– react@15.6.1
    +– react-dom@15.6.1
    +– react-router-dom@4.1.2
    `– react-scripts@0.9.5

    • Weird. I had to reinstall react-scripts. The original npm install command didn’t install it correctly or something.

      Both npm start commands run, I changed the mongodb URL to localhost/test. It connects.

      App still isn’t working. When I enter in an item into add-item route it takes me to the index but it isn’t listed.

  5. I tracked down the problem. I don’t know the fix. HOPEFULLY you can help me out.

    axios isn’t posting from ItemService. None of those calls work.
    I can use postman to hit “http://localhost:4200/items/add/post” with { ‘item ‘: ‘test’ } and I get a response of “Item added successfully”

    however when I try and do it via the Add-Item page I get nothing.

    I setup a test using axios in the app.js file. Just to see if I could get it to post and it worked there fine. No issues.

    So why doesn’t it work from ItemService? Is there some axios setup I’m missing?

  6. In EditItem.js file, how is it working

    this.props.match.params.id

    please tell full cycle of this step.
    or give any link

  7. So, there is a proxy setting that has to go in the package.json file of the front end (http://localhost).
    You didn’t need it for this tutorial because you used a mongodb connection from an external source.
    That solved my issue, I hope this helps someone.

    • I had the same problem with Axios. Can someone explain in more detail how to solve? If we don’t need it then what do we do instead of calling it? Thanks.

  8. Great tutorial, I was looking for something like this just to get my feet wet. I did find a problem though:

    // ItemService.js

    deleteData(id){
    axios.get(‘http://localhost:4200/items/delete/’+id)
    .then(console.log(‘Deleted’).catch(err => console.log(err))
    }

    Is missing a closing param on the console.log(‘Deleted) (or then) and should should be
    // ItemService.js

    deleteData(id) {
    axios.get(‘http://localhost:4200/items/delete/’ + id)
    .then(console.log(‘Deleted’))
    .catch(err => console.log(err))
    }

  9. Hi,

    The problem is that I cannot get to localhost:4200
    And when I do an npm start it says
    “Something is already running on port 3000”

  10. Good Tutorial. Thank you. I need clarrification in package.json if i mentioned “start”: “nodemon app.js”, it runs localhost:4200 (serverside) if i want to run lient side which is running in (port:3000)
    how to run? it is not run in same cli. should i need to change it npm start then run ? Please clarrify me

    • Both projects are different. For the front end, you can use npm start and from the backend, you can use the same, if your projects are in one then one script would be an npm start and another would be npm run dev.

  11. Yo bro. I have done your awesome tutorial and really glad because you have shown how to use Axios module instead of fetch. It ran very well, both on front-end and back-end. I think I have to spend a lil more time to understand the React library. Especially the props, states, and components.

  12. Can you explain why in ItemService’s all axios call can’t access setState() method? Within then() block, this.setState() is undefined. Hence, it is going into catch() block.

  13. Thanks, nice work.

    One thing, how can I get the state to update and re-render automatically when I delete an item? I have read one of the advantages of React is its quick re-rendering process. But this tutorial relies on refreshing the page. Thanks for your input.

  14. Hello Krunal,

    This is a really awesome tutorial. It is a very clear tool for developing a deeper understanding of these concepts. I have gained a lot from this read. I am having one issue though. Every time I attempt to connect to localhost 4200 the connection is refused. I am getting this error in the console when I try to add an item:
    xhr.js:178 OPTIONS http://localhost:4200/items/add/post net::ERR_CONNECTION_REFUSED
    Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:87).

    I know this is a little vague, but I was hoping that you might have some idea of what the problem is and can steer me in the right direction to fix it.

    Thank you again.

  15. Thanks a lot for valuable tutorial to begin with react js .
    Nice to have some guidance how to implement item-index page update without refresh after update particular item .

  16. This is one of the most clear and definitive tutorial on setting up a MERN project. THANK YOU SO MUCH!!

    The final note says that a refresh is not worth it in React.js.
    This project clearly needs refreshing.

    how do i make a completely reactive NODEJS + REACTJS application?

  17. You need to add a line like this right before app.listen in app.js:
    app.get(‘/’, function (req, res) {
    res.send(‘Hello Express!’);
    });

  18. I finished the tutorial, but when I got to http://localhost:3000/index it doesn’t load any items and I get the following message in the console:

    VM91:1 GET http://localhost:4200/items 404 (Not Found)
    (anonymous) @ VM91:1
    dispatchXhrRequest @ xhr.js:179
    xhrAdapter @ xhr.js:12
    dispatchRequest @ dispatchRequest.js:59
    Promise resolved (async)
    request @ Axios.js:51
    Axios.(anonymous function) @ Axios.js:61
    wrap @ bind.js:9
    componentDidMount @ IndexItem.js:13
    commitLifeCycles @ react-dom.development.js:11505
    commitAllLifeCycles @ react-dom.development.js:12294
    callCallback @ react-dom.development.js:1299
    invokeGuardedCallbackDev @ react-dom.development.js:1338
    invokeGuardedCallback @ react-dom.development.js:1195
    commitAllWork @ react-dom.development.js:12415
    workLoop @ react-dom.development.js:12687
    callCallback @ react-dom.development.js:1299
    invokeGuardedCallbackDev @ react-dom.development.js:1338
    invokeGuardedCallback @ react-dom.development.js:1195
    performWork @ react-dom.development.js:12800
    scheduleUpdateImpl @ react-dom.development.js:13185
    scheduleUpdate @ react-dom.development.js:13124
    scheduleTopLevelUpdate @ react-dom.development.js:13395
    updateContainer @ react-dom.development.js:13425
    (anonymous) @ react-dom.development.js:17105
    unbatchedUpdates @ react-dom.development.js:13256
    renderSubtreeIntoContainer @ react-dom.development.js:17104
    render @ react-dom.development.js:17129
    ./src/index.js @ index.js:11
    __webpack_require__ @ bootstrap 5b38093e1ef905914907:669
    fn @ bootstrap 5b38093e1ef905914907:87
    0 @ logo.svg:1
    __webpack_require__ @ bootstrap 5b38093e1ef905914907:669
    (anonymous) @ bootstrap 5b38093e1ef905914907:715
    (anonymous) @ bundle.js:719
    IndexItem.js:18 Error: Request failed with status code 404
    at createError (createError.js:16)
    at settle (settle.js:18)
    at XMLHttpRequest.handleLoad (xhr.js:78)

    Please help!

    Thanks!

  19. Last code example is missing a “)” immediately after “.then(console.log(‘Deleted’)” and before .catch(). Otherwise, thank you! Great tutorial

  20. Before step 7:
    “Create a project folder and go to that directory and put the following command in your terminal.”

    Does this belong inside or outside the react-frontend directory?

  21. When you type in terminal “npm start,” it will bootstrap the server, and when we change the files, it will automatically restart.

    Switch to the chrome and hit: http://localhost:4200 We get “Hello Express” in the browser.

    Not seeing this. Cannot Get. I don’t understand why I would see this because there’s nothing in app.js to do this.

      • Thanks for the your very detailed MERN posts!

        I was following your more recent MERN tutorial https://appdividend.com/2018/04/05/react-express-tutorial-example/#Step_11_Display_the_server_data and I am getting the same error as Dan doing the post request.

        I have my directory structure a little different than yours but I am using the same port numbers on localhost. My directory looks like this;

        myApp
        *backend
        **src
        ***server
        *frontend
        **public
        **src
        ***App.js
        ***index.js

        Then I have the following scripts in my backend package.json to start the db and server:
        “scripts”: {
        “start”: “babel-node src/server/server.js –presets es2015,stage-2”,
        “dboff”: “killall mongod”,
        “dbon”: “mkdir -p ./db && mongod –dbpath ./db”
        }

        Could this difference in the directory structure be my issue?

        Then I was also confused about the setting of DB that you pass to mongoose;

        module.exports = {
        DB: ‘mongodb://localhost:27017/reactexpress’
        }

        where does “reactexpress” come from? I didn’t see this anywhere else in the tutorial or the associated Github repo.

        Thanks

  22. Hi Krunal, Thanks is a great tutorial, thank you! I keep running into this error and maybe someone can help. ON the ItemsService.js file, this line:
    .then(res => this.setState({ items: res.data }))

    gives me this error:
    TypeError: _this.setState is not a function

    … and I am nos ture hwo to fix it nay ideas?

  23. i will running code and get this error pls provide me solution
    —————
    App starting error: Error: Username contains an illegal unescaped character

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.