Antonio Pavicevac-Ortiz
Antonio Pavicevac-Ortiz

Reputation: 7729

Setting up React on the front end and Express.js as a server with Webpack 4

Right now I have everything working in regards to React and webpack:

Here is my webpack.config.js

const HtmlWebPackPlugin = require('html-webpack-plugin');
const path = require('path');

module.exports = {
  entry: {
    index: './client/index.js',
  },
  output: {
    filename: '[name].bundle.js',
    path: path.join(__dirname, 'public'),
  },
  devServer: {
    contentBase: path.join(__dirname, 'public'),
    port: 3000,
  },

 /* module info */
  ......
 /* module info */

 plugins: [
    new HtmlWebPackPlugin({
      filename: './index.html',
      template: './src/index.html',
    }),
  ],
};

When running npm run dev this kicks off the webpack-dev-server on localhost:3000 \o/

Now I would also like to use express to serve data from a route or api and have react on the front end make calls to it as well.

My Express setup:

const express = require('express');
const app = express();
const path = require('path');

app.set('port', process.env.PORT || 8016);

const issues = [
  {
    id: 1,
    status: 'Open',
    owner: 'Ravan',
    created: new Date('2016-08-15'),
    effort: 5,
    completionDate: undefined,
  },
  {
    id: 3,
    status: 'Assigned',
    owner: 'Eddie',
    created: new Date('2016-08-16'),
    effort: 14,
    completionDate: new Date('2016-08-30'),
    title: 'Missing bottom border on panel',
  },
]; // global data

app.use(express.static(path.join(__dirname, '..', 'public')));

app.get('/api/issues', (req, res) => {
  var metadata = { total_count: issues.length };
  res.json({ _metadata: metadata, records: issues });
});

// sends index.html
app.use('*', (req, res) => {
  res.sendFile(path.join(__dirname, '..', 'public/index.html'));
});

app.listen(app.get('port'), function(error) {
  console.log(`App started on port ${app.get('port')}!`);
});

module.exports = app;

So you can see express is going to run on http://localhost:8016 and react on http://localhost:3000. Is there a way to have them run on the same port? If not can you explain why?

Thanks in advance!

Upvotes: 0

Views: 220

Answers (1)

Arnold Gandarillas
Arnold Gandarillas

Reputation: 4322

Is not possible because you can't run two servers in the same port (if that's possible I don't have that knowledge yet :P).

What you can do to make request to your api is to setup the devServer's proxy option:

devServer: {
  contentBase: resolve(__dirname, 'public'),
  clientLogLevel: 'warning',
  historyApiFallback: true,
  host: '0.0.0.0',
  hot: true,
  port: 3000,
  proxy: {
    '/api/*': 'http://localhost:8016'
  }

Now you'll be able to make to make request like this from react:

axios.get('/api/issues').then((res) => { console.log(res.data) })

You can review the doc here.

Upvotes: 2

Related Questions