簡體   English   中英

如何將Heroku API(服務器/ node-express)連接到自定義域gh-pages

[英]How to connect Heroku API(server/node-express) to custom domain gh-pages

我在gh頁上托管自定義域網站(react / webpack),並連接到Heroku上的服務器(node-express)。

如何連接到Heroku服務器? 我收到sendmailer的服務器連接錯誤,該錯誤在localhost上正常運行。

無法加載資源:net :: ERR_CONNECTION_REFUSED

本地主機:9080 / api / reserve:1

我已經嘗試過這些條件,以查找window.location是否包含localhost。

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

  2. window.location.hostname ==='本地主機';

如果條件為真,則返回“ 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。

我改為通過檢查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,
    };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM