Ad

How To Connect Heroku API(server/node-express) To Custom Domain Gh-pages

- 1 answer

I am hosting custom domain website(react/webpack) on gh-pages and connect to server (node-express) on Heroku.

How can I connect to Heroku server ? I am getting a server connection error for sendmailer which works fine on localhost.

Failed to load resource: net::ERR_CONNECTION_REFUSED

localhost:9080/api/reserve:1

I have tried these conditions to find out if window.location contains localhost.

  1. !!window.location.href.indexOf('localhost');

  2. window.location.hostname === 'localhost';

if the condition is true, return 'http://localhost:9080' or 'https://yuchung.herokuapp.com'

I have cors setup on node server.

config.js

const IS_DEV_MODE = window.location.hostname === 'localhost';
const URL = IS_DEV_MODE
  ? 'http://localhost:9080'
  : 'https://yuchung.herokuapp.com';

module.exports = {
  API_HOST: URL,
};

server.js

const express = require('express');
const path = require('path');
const webpack = require('webpack');
const cors = require('cors');
const logger = require('morgan');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const devMiddleware = require('webpack-dev-middleware');
const hotMiddleware = require('webpack-hot-middleware');
const config = require('../webpack.dev');

require('dotenv').config();

const app = express();

const isProd = process.env.NODE_ENV === 'production';
const corsOptions = {
  origin: 'https://yu-chung.com',
  optionsSuccessStatus: 200,
};

app.use(cors(corsOptions));
app.use(logger('dev'));
app.use(
  bodyParser.urlencoded({
    extended: true,
  }),
);
app.use(bodyParser.json());
app.use(cookieParser());

const DIST_DIR = path.join(__dirname, '../', 'public/dist');
const HTML_FILE = path.join(DIST_DIR, 'index.html');

if (!isProd) {
  const compiler = webpack(config); 
  app.use(
    devMiddleware(compiler, {
      hot: true,
      noInfo: true,
      publicPath: config.output.publicPath,
    }),
  );
  app.use(
    hotMiddleware(compiler, {
      log: console.log, // eslint-disable-line
      heartbeat: 10 * 1000,
    }),
  );

  app.get(/^\/(?!api\/)(?!assets\/)(?!.*\.json$).*/, (req, res, 
next) => {
    compiler.outputFileSystem.readFile(HTML_FILE, (err, result) => {
      if (err) {
        return next(err);
      }
      res.set('content-type', 'text/html');
      res.send(result);
      return res.end();
    });
  });
} else {
  app.use(express.static(DIST_DIR));
  app.get('*', cors(corsOptions), (req, res) => 
res.sendFile(HTML_FILE));

  app.get('/', cors(corsOptions), (req, res) => {
    res.redirect('https://yu-chung.com');
  });
}

app.use('/api', require('./api'));

const PORT = process.env.PORT || 9080;
app.listen(PORT, () => {
  console.log(`Sever is listening on ${PORT} in 
${process.env.NODE_ENV}`);
});

reserveAction.js

 export const reserve = reserveInfo => dispatch => {
     dispatch({
       type: types.RESERVE_REQUEST,
     });
     return axios
       .post(`${API_HOST}/api/reserve`, reserveInfo)
       .then(() =>
         dispatch({
           type: types.RESERVE_SUCCESS,
           reserveInfo,
         }),
       )
       .catch(error =>
         dispatch({
            type: types.RESERVE_FAILURE,
            error,
          }),
       );
    };

It am expecting the client make https://yuchung.herokuapp.com/api/reserve call instead of localhost:9080/api/reserve.

Ad

Answer

I resolved the problem by checking on process.env.NODE_ENV instead.

 let IS_DEV_MODE = false;
    if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
      IS_DEV_MODE = true;
    }

    const URL = IS_DEV_MODE
      ? 'http://localhost:9080'
      : 'https://yuchung.herokuapp.com';

    module.exports = {
      API_HOST: URL,
    };
Ad
source: stackoverflow.com
Ad