如何将Heroku API(服务器/ node-express)连接到自定义域gh-pages

时间:2018-12-23 08:49:22

标签: node.js express github-pages heroku-api

我在gh页上托管自定义域网站(react / webpack),并连接到Heroku上的服务器(node-express)。

如何连接到Heroku服务器? 我收到sendmailer的服务器连接错误,该错误在localhost上正常运行。

  

无法加载资源:net :: ERR_CONNECTION_REFUSED

     

localhost:9080 / api / reserve:1

我已经尝试过这些条件来确定window.location是否包含localhost。

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

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

  4.   

如果条件为真,则返回'http://localhost:9080'或'https://yuchung.herokuapp.com'

我在节点服务器上设置了cors。

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,
          }),
       );
    };

期望客户端拨打https://yuchung.herokuapp.com/api/reserve而不是localhost:9080 / api / reserve。

1 个答案:

答案 0 :(得分:0)

我通过检查process.env.NODE_ENV来解决了这个问题。

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