Call Express API in React using Webpack

Hussain
4 min readOct 13, 2017

--

Here, I am using Webpack with React and Nodejs.
Webpack is a module bundler for modern JavaScript applications. When Webpack processes your application, it recursively builds a dependency graph that includes every module your application needs, then packages all of those modules into a small number of bundles — often only one — to be loaded by the browser.
With Webpack, I am trying to fetch Backend API using ‘fetch’ method, already included in create-react-app. I will fetch the data from the server side and display it on the Frontend using Reactjs.

Example : express-webpack

Step 1: Create the React App

First, I will Install the create-react-app globally, then Install all the dependencies which are required for the project. -g for globally & i for install.

$ npm install create-react-app -g 
$ create-react-app express-webpack
$ cd express-webpack
$ npm i -D webpack webpack-dev-middleware webpack-dev-server html-webpack-plugin
$ npm i -D babel-loader babel-core babel-preset-env babel-preset-es2015
$ npm i -D url-loader style-loader css-loader rimraf

Step 2: Create Some file like webpack.config.js, .babelrc, server.js.

Create .babelrc and insert this code

{ 
"presets": [ "es2015", "react" ]
}

Create webpack.config.js and copy the code.

Here I am runnig the webpack server on port 3002 in devServer.

Html-webpack-plugin: It is a webpack plugin that simplifies the creation of HTML files to serve your webpack bundles. You can use this plugin to generate an HTML file for you or supply your own template using lodash templates.
Entry: The entry point tells webpack where to start and follows the graph of dependencies to know what to bundle. You can think of your application’s entry point as the contextual root or the first file to kick off your app.
Output: The webpack output property tells webpack how to treat bundled code.
Loaders: webpack treats every file (.css, .html, .scss, .jpg, etc.) as a module. Loaders in webpack transform these files into modules as they are added to your dependency graph.
Plugins: plugins are most commonly used to perform actions and custom functionality on “compilations” or “chunks” of your bundled modules.
devServer: webpack-dev-server can be used to quickly develop an application.

If you’re using dev-server through the Node.js API, the options in devServer will be ignored. Pass the options as a second parameter instead: new WebpackDevMiddleware(compiler, {…}).

var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
context: path.resolve(__dirname, "src"),
devtool: debug ? "inline-sourcemap" : false,
entry: {
app: "./index.js"
},
module: {
rules: [
{
test: /\.css$/,
use : ['style-loader', 'css-loader']
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
},
{
test: /\.(woff2?|svg)$/,
use: [{
loader: 'url-loader',
options: {
limit: 10000,
name: 'fonts/[name].[ext]'
}
}]
},
],
},
devServer : {
contentBase: './dist',
compress: true,
port: 3002,
stats: 'errors-only',
open: true,
hot: true,
},
output: {
path: path.resolve(__dirname ,"dist"),
filename: "[name].bundle.js",
publicPath: '/'
},
plugins: [
new HtmlWebpackPlugin({
title:'React js',
template:'./public/index.html' ,
minify : {
collapseWhitespace : false
},
hash : true
}),
new webpack.HotModuleReplacementPlugin(),
]
};

Create server.js, which is a node server on port 3000.

webpack-dev-middleware :It’s a simple wrapper middleware for webpack. It serves the files emitted from webpack over a connect server. This should be used for development only.

const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const app = express();
const config = require('./webpack.config.js');
const compiler = webpack(config);
// Tell express to use the webpack-dev-middleware and use the webpack.config.js
// configuration file as a base.
app.use(webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath
}));
app.use('/users', function (req, res) {
res.json(
[{ result : 'from users' }])
});
app.use('/api', function(req, res){
res.json(
[{ api : 'from api' }])
});
// Serve the files on port 3000.
app.listen(3000, function () {
console.log('Example app listening on port 3000!\n');
});

Step 3. Do Some changes

Edit the package.json and add some scripts for easily running the server. Here “dev” is for webpack server and “server” is for node server.

 “dev”: “./node_modules/.bin/webpack-dev-server -d — watch”,
“prod”: “npm run clean && NODE_ENV=production ./node_modules/.bin/webpack -p”,
“clean”: “./node_modules/.bin/rimraf ./dist/*”,
“server”: “nodemon server.js”,

And Move the public folder in src directory.

Step 4. Fetch the Data from frontend (Reactjs) in src/App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
constructor(){
super();
this.state ={users: []};
}

componentDidMount() {
fetch('/users')
.then(res => res.json())
.then(users => this.setState({ users }));
}

render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<div>
<h1>User</h1>
{this.state.users.map(user =>
<div key={1}><h3>Name: {user.name}</h3></div>
)}
</div>
</div>
);
}
}

Step 5. Run the node server

For running server

$ npm run server

For creating build or webpack production

$ npm run prod

--

--