当前位置: 代码网 > it编程>前端脚本>Vue.js > linux运行vue编译后的项目方式

linux运行vue编译后的项目方式

2026年03月23日 Vue.js 我要评论
如果你的 vue 项目使用了 history 模式(而非默认的 hash 模式),在纯静态服务器中会出现类似的问题。因为 vue router 的 history 模式要求所有未匹配的路径都重定向到

如果你的 vue 项目使用了 history 模式(而非默认的 hash 模式),在纯静态服务器中会出现类似的问题。因为 vue router 的 history 模式要求所有未匹配的路径都重定向到 index.html,以便 vue 前端处理路径。

首先在本地执行npm run build编译项目,会生成一个dist的项目源码文件

1.创建一个简单的 http 服务器

修改你的 server.js,确保所有未匹配的请求都返回 index.html。

const http = require('http');
const fs = require('fs');
const path = require('path');

const port = 14515;

http.createserver((req, res) => {
    let filepath = path.join(__dirname, req.url === '/' ? '/index.html' : req.url);

    fs.readfile(filepath, (err, data) => {
        if (err) {
            // 如果文件不存在,返回 index.html
            fs.readfile(path.join(__dirname, 'index.html'), (err, indexdata) => {
                if (err) {
                    res.writehead(500, { 'content-type': 'text/plain' });
                    res.end('500 internal server error');
                } else {
                    res.writehead(200, { 'content-type': 'text/html' });
                    res.end(indexdata);
                }
            });
        } else {
            // 返回找到的文件
            const ext = path.extname(filepath).tolowercase();
            const mimetypes = {
                '.html': 'text/html',
                '.js': 'application/javascript',
                '.css': 'text/css',
                '.json': 'application/json',
                '.png': 'image/png',
                '.jpg': 'image/jpg',
                '.gif': 'image/gif',
                '.svg': 'image/svg+xml',
            };

            res.writehead(200, { 'content-type': mimetypes[ext] || 'application/octet-stream' });
            res.end(data);
        }
    });
}).listen(port, () => {
    console.log(`server running at http://0.0.0.0:${port}/`);
});

2.运行

在 dist 目录下启动服务器:

node server.js

nohup node server.js &  //在后台可以运行

项目目录

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com