node服务适配前端路由

可能网上已经大把相似的资料了,在这里只不过是总结一下html

用react举例前端

在react-router 4.0版本中,BrowserRouter和HashRouter均可以实现前端路由的功能,区别是前者基于rul的pathname段,后者基于hash段。node

前者:http://127.0.0.1:3000/a/breact

后者:http://127.0.0.1:3000/#/a/b(有个#老是让人难以接受)后端

这样的区别带来的直接问题就是当处于二级或多级路由状态时,刷新页面,BrowserRouter会将当前路由发送到服务器(由于是pathname),而HashRouter不会(由于是hash段)。浏览器

一般咱们都是使用BrowserRouter,前端路由在刷新浏览器的时候会被认为是服务器的路由被发送到服务器,然而服务器并无配置相关的路由,而后浏览器当前的连接就会显示404。bash

能够在node代码中添加这么一段代码:服务器

app.use(function(req, res, next) {
        fs.readFile(path.resolve(__dirname, '../server_file/dist/mobile.html'), function(err, data){
            if(err){
                console.log(err);
                res.send('后台错误');
            } else {
                res.writeHead(200, {
                    'Content-type': 'text/html',
                    'Connection':'keep-alive'
                });
                res.end(data);
            }
        })
    });
复制代码

这段代码的意思就是说,只要服务器接收到浏览器发送过来的路由,在这个路由没有在node中配置的状况下,都会尝试着把前端页面发送回去,而后浏览器再去匹配前端路由。react-router

我认为这其中须要注意的地方:app

前端路由和后端路由不能出现重复。

多个单页面的时候应该如何配置?

前端打包多个单页面应该不是新鲜话题了,工做中有时候也会用到。

前端文件在后端也是经过相应路由来发送的,好比说/mobile,就是发送mobile相关的html文件,/pc就是发送pc相关的html文件。

在mobile的这个单页面中,须要node适配前端的路由,在pc的这个单页面中,也须要node适配前端路由。要解决的问题就是让node知道浏览器当前打开的究竟是mobile仍是pc。

个人作法是前端路由能适配node对应的路由,而后跟上述方法同样,把多余的路由的请求统一返回对应文件

mobile前端路由这样:

<Route  path="/mobile/main" component={App} />
<Route path="/mobile/main/login" component={Login} />
复制代码

后端路由这样:

app.use('/mobile', function(req, res, next) {
        fs.readFile(path.resolve(__dirname, '../server_file/dist/mobile.html'), function(err, data){
            if(err){
                console.log(err);
                res.send('后台错误');
            } else {
                res.writeHead(200, {
                    'Content-type': 'text/html',
                    'Connection':'keep-alive'
                });
                res.end(data);
            }
        })
    });
复制代码

PC前端路由这样:

<Route  path="/pc/main" component={App} />
<Route path="/pc/main/login" component={Login} />
复制代码

后端路由这样:

app.use('/pc', function(req, res, next) {
        fs.readFile(path.resolve(__dirname, '../server_file/dist/pc.html'), function(err, data){
            if(err){
                console.log(err);
                res.send('后台错误');
            } else {
                res.writeHead(200, {
                    'Content-type': 'text/html',
                    'Connection':'keep-alive'
                });
                res.end(data);
            }
        })
    });
复制代码

完!

相关文章
相关标签/搜索