gpt4 book ai didi

javascript - 让所有网站路径在 express 中加载相同的静态网站

转载 作者:行者123 更新时间:2023-11-30 00:07:58 25 4
gpt4 key购买 nike

在我的 express 服务器中,我想让所有路径都加载同一个静态网站,我尝试使用以下代码来实现:

const express = require('express');
const app = express();

app.use('*', express.static('build'));
app.listen(3000);

不幸的是,当我导航到本地主机上的任何路径时,出现以下控制台错误:

:3000/main.js/:1 Uncaught SyntaxError: Unexpected token <

当试图查看有错误的 JS 文件时,它似乎在它的位置提供 index.html。

我知道这是由于通配符引起的,但我想不出一种方法可以从静态服务器中彻底排除所有文件名和路径。

最佳答案

我认为您正在寻找更像这样的东西..app.use(express.static('public')

如果你的树看起来像

ProjectName
| server.js
| public
| index.html

您不需要 * 作为参数,因为设置 express.static 会将文件夹设置为公开查看。这就是您分离服务器代码和客户端代码的方式。小心不要公开你的整个项目目录,因为这样人们就可以访问你的服务器代码。这就是为什么您的客户文件应该保存在公共(public)文件夹或 www 文件夹中(常见做法)

--编辑

//this will server css, and js files so they can be linked into the html
app.use(express.static(__dirname + '/public'));

//this will force all url's except the public files to be given the index.html file.
app.use('*', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});

关于javascript - 让所有网站路径在 express 中加载相同的静态网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37750956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com