快速问题,使用反应-路由器。我很难让服务器处理pushState (如果这是正确的话)。最初,我使用的是一个名为connect-history-api-fallback的模块,它是一种中间件,使我只能够从dist目录中服务器上的静态文件。访问客户端www.example.com显然是有效的,而且我可以浏览整个站点,另外,在www.example.com/about之类的任何路径上都可以进行刷新。
但是,我最近在我的Express服务器上为React /client添加了一个简单的API端点到ping。现在的问题是,虽然我可以让初始页面加载工作(因此/api/news调用可以工作,以便从远程服务获取数据),但我不能再在任何其他路由上进行刷新。例如,现在访问www.example.com/about将导致对/about的GET请求失败。我该怎么补救呢?真的很感谢你的帮助!PS -不确定这是否重要,但我正在考虑稍后实现服务器端呈现。
import express from 'express';
import historyApiFallback from 'connect-history-api-fallback';
import config from '../config';
import chalk from 'chalk';
import fetch from 'node-fetch';
import path from 'path';
const app = express();
// FIXME: Unsure whether or not this can be used.
// app.use(historyApiFallback({
// verbose : true
// }));
//// DEVELOPMENT MODE ONLY - USING EXPRESS + HMR ////
/* Enable webpack middleware for hot module reloading */
if (config.get('globals').__DEV__) {
const webpack = require('webpack');
const webpackConfig = require('../build/webpack/development_hot');
const compiler = webpack(webpackConfig);
app.use(require('./middleware/webpack-dev')({
compiler,
publicPath : webpackConfig.output.publicPath
}));
app.use(require('./middleware/webpack-hmr')({ compiler }));
}
//// PRODUCTION MODE ONLY - EXPRESS SERVER /////
if (config.get('globals').__PROD__) {
app.use(express.static(__dirname + '/dist'));
}
//// API ENDPOINTS FOR ALL ENV ////
app.get('/api/news', function (req, res) {
fetch('http://app-service:5000/news')
.then( response => response.json() )
.then( data => res.send(data) )
.catch( () => res.sendStatus(404) );
});
// Wildcard route set up to capture other requests (currently getting undexpected token '<' error in console)
app.get('*', function (req, res) {
res.sendFile(path.resolve(__dirname, '../dist', 'index.html'));
});
export default app;发布于 2015-12-17 22:35:20
Express通过实现一系列您通过.use“插入”的中间件来工作。最酷的是,你的路线也只是中间件--所以你可以把它们分开,在你的历史退步之前把它们分开,然后只有那些通过你的路线的请求(例如,不匹配任何路线)才会遇到退路。
尝试如下所示:
const app = express();
// ...
var routes = exprss.Router();
routes.get('/api/news', function (req, res) {
fetch('http://app-service:5000/news')
.then( response => response.json() )
.then( data => res.send(data) )
.catch( () => res.sendStatus(404) );
});
app.use(routes);
app.use(historyApiFallback({
verbose : true
}));https://stackoverflow.com/questions/34344270
复制相似问题