V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
tslyjlovedota
V2EX  ›  Node.js

关于 vue 打包之后,nodeJs 后端配置

  •  
  •   tslyjlovedota · 2017-11-03 11:36:04 +08:00 · 6944 次点击
    这是一个创建于 2364 天前的主题,其中的信息可能已经有所发展或是发生改变。

    关于使用 vue 路由的 history 模式。

    在打包后的文件里有一个 index.html. 我想通过 node 启动一个服务器,去模拟真实服务器的状态。 看了 vue 的官方文档,提示我用一个第三方的 connect-history-api-fallback 去 redict 地址。。。

    但是我配置过后死活不行,页面通过点击进入其他的路由是可以的,一刷新就没了,报 404.

    这是我 nodejs 的配置,直接放在 index.html 文件夹内部的

    const express = require('express') const webpack = require('webpack')

    const app = express()

    var history = require('connect-history-api-fallback'); // // handle fallback for HTML5 history API ///启动的时候使用了 node 服务器.....所以不会出问题了。。。

    var middleware = history({

    rewrites: [ { from: /^/.*$/, to: function(context) { return '/'; } } ], verbose: true, disableDotRule: true, htmlAcceptHeaders: ['text/html', 'application/xhtml+xml'] })

    app.use(express.static(__dirname)) app.use(middleware)

    const port = process.env.PORT || 8089 module.exports = app.listen(port, () => { console.log(Server listening on http://localhost:${port}, Ctrl+C to stop) })

    ////刷新的时候没有了。。。

    6 条回复    2017-11-21 11:42:54 +08:00
    whypool
        1
    whypool  
       2017-11-03 11:50:27 +08:00
    1,用路由控制;
    2,路由规则泛匹配;
    eg:

    app.use('/*',function(req,res,next){
    res.sendFile('../public/index.html');
    });

    这样拦截所有的根请求都会发 index 首页过去,然后前端再渲染
    duan602728596
        2
    duan602728596  
       2017-11-03 11:53:14 +08:00
    router.get(/^\/[^\.]*$/, async (ctx, next)=>{
    const { status, body } = await readFile(serverFile + '/index.html');

    ctx.state = status;
    ctx.type = 'text/html';
    ctx.body = body;

    await next();
    });

    我后端用的是 koa2 服务器,所有的 /Path/To 格式的 不匹配带扩展名的 url 都定向到 index.html,express 同理
    tslyjlovedota
        3
    tslyjlovedota  
    OP
       2017-11-03 13:36:58 +08:00
    @whypool 这个成功了...相当于我不用 ('connect-history-api-fallback'),官方推荐的插件了。。也可以,奇怪,,,官网竟然没有推荐你这种模式
    tslyjlovedota
        4
    tslyjlovedota  
    OP
       2017-11-03 13:38:52 +08:00
    @duan602728596 对的,应该可以了,但是使用官方推荐 history 插件,死活不回重新指向 index.html,可能我的配置路径写的有问题?
    nidaye999
        5
    nidaye999  
       2017-11-03 13:44:54 +08:00
    ioNull
        6
    ioNull  
       2017-11-21 11:42:54 +08:00
    vuejs 用的是 HTML5 pushstate,你可以直接用 nginx 之类的设置就好了,不需要用 nodejs 来路由
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3318 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 12:15 · PVG 20:15 · LAX 05:15 · JFK 08:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.