AppDividend
Latest Code Tutorials

MERN Stack Tutorial

MERN Stack Tutorial With Example From Scratch

23,518

Get real time updates directly on you device, subscribe now.

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

React.js is very famous UI library provided by Facebook. We are using Express web framework, which provides us Routing functionality to our application as well as Middlewares through which we can filter our HTTP requests.

The basic requirement for taking this course

  1. Node.js Express MongoDB Tutorial
  2. Beginner’s Guide To Setup React v15.4.2 Environment  (If you want to Start React.js from scratch)

MERN Stack Tutorial

First, we need to build front-end using React.js, set up routing, and create a basic form.

After that, we build backend using the express framework.

Step 1: Draft ReactJS Application.

For set up react application at the front end, we use create-react-app starter kit to initialize our application, so go to the terminal and if you are Windows user, please open CMD in Administrator mode and type 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 following command

create-react-app react-frontend

I have given our project’s name react-frontend, you can give 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 following command.

npm start

At http://localhost:3000/

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

MERN Stack Tutorial

Step 2: Install React and ReactDOM.

Now, we need to set up the react-router-dom package. It provides us 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 routing package and it is based on components.

I am providing you my package.json file, so you do not worry about it, and if you have any problem, then please check out your all the dependency version 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, which is 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, so I am importing all of the modules from downloaded packages. Here  I am rendering routes as components. Till now, I have defined only one route, which is our app route.

Step 3: Make components folder.

Create one directory in src called components.

Related Posts
1 of 14

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;

Now, we need to import this component to index.js file and also 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 this URL: http://localhost:3000/add-item

You will see like “Welcome to Add Item.”

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

You will see like “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 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 a bootstrap official website and put 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 className property instead of class in React application.

Now, 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 state also changes and set the value according to it. 

After the user submits the form, the state value, which is set, 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 request to the server.

Step 5: Make ItemService.js file.

Create a service file in 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 axios library, so I have sent the post request to the server, which is express node server.

Now we just need to import this file in 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 call its sendData method. Pass the input value as a parameter and ready to go.

Step 6: Make a nodejs express project.

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

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

npm init

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

Step 7: Install expressjs framework.

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

npm install --save express

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

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

Step 8: Make app.js file.

Create a file in root called “app.js.” This file is our main server file in which it bootstraps the node server, and also it serves some static files. 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, then we can use one package called nodemon. It is kind of server that reloads every time we change the file.

npm install -g nodemon

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

"start": "nodemon app.js"

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.

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 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 mongoose schema.

Create a model for Mongoose Schema. So create a new directory in the src folder called models and then create another file in that 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 access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:3000’ is therefore not allowed access.

Possible Solutions:

Use middleware package called ‘cors‘ in express application

npm install --save cors

Include this in app.js file in node.js Express project and add as a middleware

//app.js

var cors = require('cors');

app.use(cors());

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

You can see one form, put the item name and if your backend database connection is perfectly fine then, you can insert the data into the mongo database, and you can redirect back to your home router.

Step 12: Register the routes at the front end.

Next, we need to register index route, so that we can 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 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, nd in response, we are getting the data.

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

So 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, remaining is editing and deleting.

Step 13: Make editItem.js file.

Create a new edit file in components called “EditItem.js.” 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 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.

Now, updating our data so, we need to change 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;

Also, we need to code the update function in 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))
  }

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

Step 15: Delete the data.

Now, 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;

Next step is to code ItemService.js file

// ItemService.js

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

Now, 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 just showcase that 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 Tutorial

  1. Clone The reactfrontend project repo.
  2. Go to the project folder
  3. 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 app.js file change MongoDB URI to your particular URI
  9. run the command “npm start
  10. Now, go this URL: http://localhost:3000/add-item

If you still have any doubt in MERN Stack Tutorial then ask in a comment below I am happy to help you out.

62 Comments
  1. Jeff Scott says

    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).

    1. Krunal says

      Thanks, Man, I really appreciate that.

    2. Jeff Scott says

      I spoke too soon!

      When I hit URL:4200/foo I get the error “Cannot GET /foo”

      Any idea? I’m upto step 13.

      1. Krunal says

        Have you define the route for the foo?

        1. Jeff Scott says

          My index.js is a direct copy paste from step 13 and app.js from step 10.

          I don’t see anything in app.js that would connect it to index.js. What am i missing?

          Do you have a git site for this tutorial so i can compare files?

  2. Arpit says

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

    1. Krunal says

      Yes, Thanks For The Draw Me Your Attention.

      1. Jeff Scott says

        In step 10 app.js var ItemRouter should require ItemRouter not ItemRoutes.

        How come the git site doesn’t have the app.js file?

        1. Krunal says

          I have sent you this link already, https://github.com/KrunalLathiya/expressbackend

        2. Krunal says

          This file app.js is in the backend folder, react is for the frontend, it does not contain app.js

          1. Jeff Scott says

            Yup, you’re right, my bad. I didn’t look in that folder. I assumed it was in the root because that’s where it is in the tutorial.

            I’m pretty new, I don’t really understand the separation of duties as good as you do.

          2. Krunal says

            It’s okay 🙂

        3. Krunal says

          I have posted two links in that post, have you not seen yet..It is in the last

  3. Jeff Scott says

    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. Jeff Scott says

    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

    1. Jeff Scott says

      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. Jeff Scott says

    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. Arpit says

    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. Jeff Scott says

    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.

    1. Matthew says

      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. ML says

    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. aruna says

    Very good tutorial for starters.

    1. Krunal says

      Thanks, buddy!!..Keep Sharing with fellow mates.

  10. Parinaaz says

    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”

    1. Krunal says

      Please check there is another server running on port: 3000

      1. Parinaaz says

        Yup checked
        Solved
        Thank you

  11. Arpit says

    In http://localhost:3000/index page
    when we delete any item at this page then page should refresh and that content should not show more. How ?

  12. pradeepa says

    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

    1. Krunal says

      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.

  13. Ahmad Irfan Mohammad Shukri says

    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.

  14. Michael says

    Could you also add an example that shows how to deploy to heroku or other host.

    1. Krunal says

      Sure, I will do that.

  15. Andy says

    Very nice and updated tutorial

  16. Darshan says

    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.

  17. Gurujot Singh says

    In step 13
    TableRow.js

    You should define, import { Link} from ‘react-router-dom’
    Which is done in Step 15.

  18. Mango says

    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.

  19. Luke says

    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.

  20. Kanchana says

    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 .

  21. Dan says

    I get stuck at step 8. When I run npm start I can’t see anything in the browser at/4200 only “Cannot GET /”

    1. Patrick says

      try this
      “`
      app.get(‘/’, (req, res) => res.send(‘Hello Express!’))
      “`

  22. Tanmoy says

    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?

  23. Adam says

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

  24. Eric says

    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!

  25. Matt Pardini says

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

  26. Pratik says

    can’t we keep the package.json common?

  27. Raul says

    Nice tutorial… How can I deploy this?

  28. dsadsa says

    good tutorial thank you

  29. Matthe says

    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?

    1. Krunal says

      In side that directory.

  30. Matthew says

    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.

  31. Paul Fleischer-Djoleto says

    Hi Krunal, I tried the step 10 command ‘Switch to the chrome and hit: http://localhost:4200 We get “Hello Express” in the browser.’. I got Hello world at the command prompt but the browser reported ‘cannot get/’ when I typed
    http://localhost:4200/. I later typed http://localhost:4200/app.js but it could not solve the problem.

    Can you please help me to solve this prob

  32. Brian says

    “Now, add the bootstrap classes to our add-item.js page” What is the code for that?

  33. Mansi says

    i am unable to run my nodejs

    1. Krunal says

      Check the version by typing if you have correctly install or not. Type node -v

  34. Dan Collins says

    Love your MEAN tutorial!

    Question. I’ve made my post request (axios.post(‘http://localhost:4200/items/add/post’) but i get the following error:

    “OPTIONS http://localhost:4200/items/add/post net::ERR_CONNECTION_REFUSED”

    1. Dan Collins says

      *MERN

    2. Krunal says

      Start your MongoDB database server. Check your credentials.

      1. Dan Collins says

        ok. Thank you

  35. Amanda Patricia Koster says

    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?

  36. krupali says

    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

Your email address will not be published.

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