Node 路由返回vue打包资源,浏览器能成功下载资源但显示空白
发布于 6 年前 作者 BarryLiu1995 3317 次浏览 来自 问答

相关说明

本人最近弄了个业余项目,项目目录结构如下图所示:

目录结构

根目录有 frontend 和 backend,其中 frontend 是Vue构建的网页,frontend/dist 文件夹是生产环境所需的文件,即npm run build后的产物。backend 就是项目后端代码部分,其中 backend/index.js 是入口文件,在里面创建了一个HTTP 服务器。

问题之处

backend/index.js创建了HTTP服务,在浏览器地址栏输入http://localhost:8080/index.html这个地址预期效果就是:服务端就会返回frontend/dist/index.html资源,同时frontend/dist/index.html有相关css和js链接,就会下载下来然后渲染页面。但实际情况就是网页是空白,但在chrome devtool 的network调试监控没有报出错误。然后我使用postman调试相关链接,都是可以返回对应的文件。

相关代码:

http.createServer(function (request, response) {
    let url = request.url;
    console.log(url);
    let ext, filePath, contentType;
    ext = path.extname(url);
    ext = ext ? ext.slice(1) : 'unknown';
    contentType = MINE[ext];
    let contentTypeHeader = {
        "Content-Type": contentType
    };
    if (url.indexOf('/search?') !== -1) {
        ...
        ...
    } else if (url === '/robots.txt' || url === '/favicon.ico') {
        response.writeHead(200, contentTypeHeader);
        let readStream = fs.createReadStream(__dirname + url, 'utf8');
        readStream.pipe(response);
    } else {
        let tempPath = path.join('frontend/dist',url);
        let root = path.resolve(__dirname,'..');
        filePath = path.join(root, tempPath);
        console.log(filePath);
        response.writeHead(200, contentTypeHeader);
        let readStream = fs.createReadStream(filePath, 'utf8');
        readStream.pipe(response);
    }
}).listen(8080);

const MINE = {
    "css": "text/css",
    "js": "text/javascript",
    "html": "text/html",
    "ico": "application/octet-stream",
    "txt": "text/plain",
    "ttf": "application/octet-stream"
};
console.log("The server is running at port 8080");

chrome devtool:

实际情况

postman 调试:

postman调试

7 回复

只访问到了入口,路由配置默认首页是什么

@mrtanweijie 你好,首页就是index.html,位于frontend/dist/index.html。还是你意思是说前端Vue这边默认的路由页面是什么?vue的路由配置如下: frontend/src/router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home'

Vue.use(Router);

export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/index.html',
      name: 'home',
      component: Home
    }
  ]
})

昨天也遇到了一次类似的情况,不过我的错误是比较简单,是由于打包后样式出了点儿问题,能渲染出dom,但是样式全没了,dom宽高都是0~~,可以参考一下

@zhangxh1023 你好,感谢你的回复。刚刚我看了一下我的情况,发现页面DOM都没有渲染出来,这样的话感觉是打包出来的js有问题

修改一下config目录下的index.js文件,

assetsPublicPath: ‘./’

然后重启服务试试

@BarryLiu1995 path: ‘/index.html’, 有点奇怪,直接用“/” , 访问localhost:8080 ,还有看看打包配置文件是不是路径的问题

同楼上,vue的根路由用/

回到顶部