我在 gh-pages 上托管自定义域网站(react/webpack)并连接到 Heroku 上的服务器(node-express)。
如何连接到 Heroku 服务器?我收到 sendmailer 的服务器连接错误,它在 localhost 上运行良好。
加载资源失败:net::ERR_CONNECTION_REFUSED
本地主机:9080/api/reserve:1
我已经尝试了这些条件来确定 window.location 是否包含 localhost。
!!window.location.href.indexOf('localhost');
window.location.hostname === 'localhost';
如果条件为真,则返回“ http://localhost:9080 ”或“ https://yuchung.herokuapp.com ”
我在节点服务器上设置了 cors。
配置.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,
};
服务器.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。