新手请教关于Express搭建React服务器的问题

想在想要在服务器上搭建一个Node服务器server.js大致如下:

var app = express();
app.use(express.static(__dirname + '/'));
app.use(history());
app.get('/', function (req, res) {
    res.sendFile( __dirname + "/" + "index.html" );
})
app.listen(8081);

React使用React-Router做了路由,main.js大致如下:

reactDom.render(
    <Provider store={ store }>
        <Root/>
    </Provider>,
    document.getElementById("main")
)

Router大致如下:

const routesObj = (
    <Route path="/" name="App" component={ App }>
    <Route path='/home' name="Home" component={ Home }>
        <IndexRoute components={ Welcome }/>
        <Route path='/welcome' name="Welcome" component={ Welcome } />
    </Route>
    <IndexRedirect to='/home'/>
</Route>
);

export default class Root extends React.Component{
    render(){
        return <Router history={ browserHistory } routes={ routesObj }/>
    }
};

项目开发阶段一直使用的webpack-dev-server一切正常
-在浏览器直接localhost:8081访问可以访问到home
-在浏览器直接localhost:8081/home访问可以访问到home

但是以我的那个server.js启动的服务器只能localhost:8081/访问到home页面但是localhost:8081/home会找不到home,页面显示Cannot GET /home

求问大神们怎么解决,不太理解这块

阅读 4.9k
5 个回答

你通过 server.js启动的时候 是使用的express路由 也就是后端路由

而你dev-server的时候 是使用的react路由 也就是前端路由

二选其一

你可以直接访问localhost:8081/index.html

你是没清楚前端路由和后端路由

app.get('/', function (req, res) {
    res.sendFile( __dirname + "/" + "index.html" );
})

这个地方指向的是你的node服务端下的模板文件,但是你react中的webapck-dev-server中通过dev配置指向的是webapck-dev-server中的express中的template资源路径(通过html-webpack-plugin读取),两个东西其实是分属不同的服务下,可以试着用create-react-app去生成一个独立的react项目,再指向下npm run eject,查看下里面的dev-server的配置信息即可。

你需要historyApiFallback,因为你使用的是history模式而非hash模式,当你在webpack开发环境时,dev-server会帮你Fallback,但是当你使用自己的server如Express时你需要自己使用模块如connect-history-api-fallback 来解决。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题