V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
tslyjlovedota
V2EX  ›  Node.js

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

  •  
  •   tslyjlovedota · Nov 3, 2017 · 7935 views
    This topic created in 3103 days ago, the information mentioned may be changed or developed.

    关于使用 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 replies    2017-11-21 11:42:54 +08:00
    whypool
        1
    whypool  
       Nov 3, 2017
    1,用路由控制;
    2,路由规则泛匹配;
    eg:

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

    这样拦截所有的根请求都会发 index 首页过去,然后前端再渲染
    duan602728596
        2
    duan602728596  
       Nov 3, 2017
    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
       Nov 3, 2017
    @whypool 这个成功了...相当于我不用 ('connect-history-api-fallback'),官方推荐的插件了。。也可以,奇怪,,,官网竟然没有推荐你这种模式
    tslyjlovedota
        4
    tslyjlovedota  
    OP
       Nov 3, 2017
    @duan602728596 对的,应该可以了,但是使用官方推荐 history 插件,死活不回重新指向 index.html,可能我的配置路径写的有问题?
    nidaye999
        5
    nidaye999  
       Nov 3, 2017
    ioNull
        6
    ioNull  
       Nov 21, 2017
    vuejs 用的是 HTML5 pushstate,你可以直接用 nginx 之类的设置就好了,不需要用 nodejs 来路由
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2507 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 08:40 · PVG 16:40 · LAX 01:40 · JFK 04:40
    ♥ Do have faith in what you're doing.