gpt4 book ai didi

javascript - 使用 express 在 Node js 中提供 html 文件

转载 作者:搜寻专家 更新时间:2023-11-01 00:40:32 24 4
gpt4 key购买 nike

实际上,我正在尝试使用 Node js 和 express 在浏览器中提供 html 文件。不幸的是,我无法正确显示 html 文件。

代码如下:

var http = require('http');
var fs = require('fs');
// Chargement du fichier index.html affiché au client

var server = http.createServer(function(req, res) {
fs.readFile('./table.html', 'utf-8', function(error, content) {

res.writeHead(200, {"Content-Type": "text/html"});
res.end(content);
});
});

最佳答案

要为特定路由发送单个文件,请使用 res.sendFile()功能。

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

var path = require('path');

app.get('/', function(req, res) {
res.sendFile(path.resolve('path/to/my/file.html'));
});

app.listen(3000);

如果您想提供目录中的所有文件,请使用 express.static()中间件

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

app.use(express.static('path/to/my/directory'));

app.listen(3000);

关于javascript - 使用 express 在 Node js 中提供 html 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36149797/

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