【发布时间】:2023-01-20 14:44:29
【问题描述】:
当我尝试运行此代码时,我没有收到任何错误,但当我打开 loclhost 时出现空白屏幕。
const path = require("path")
const express = require("express")
app = express()
app.get("/", (req, res) => {
let fullpath = path.join(__dirname, './index.html')
console.log(fullpath)
res.sendFile(fullpath)
console.log("File sent")
res.end()
})
app.listen(5500, () => {
console.log("Server started")
})
我使用的是 linux,express 版本是 4.18.2,node 版本是 18.1.0
我在具有相同 express 版本的 Windows 机器上执行了相同的代码,并且没有任何错误。也许它与 linux 兼容性有关,或者可能与 windows 和 linux 中的路径有何不同。
到目前为止我尝试过的事情:
const path = require("path")
const express = require("express")
app = express()
app.get("/", (req, res) => {
let fullpath = path.join(__dirname, './index.html')
res.sendFile(fullpath, { root: '/' })
console.log("File sent")
res.end()
})
app.listen(5500, () => {
console.log("Server started")
})
const path = require("path")
const express = require("express")
app = express()
app.get("/", (req, res) => {
var options = {
root: path.join(__dirname)
}
let fileName = 'index.html'
res.sendFile(fileName, options)
console.log("File sent")
res.end()
})
app.listen(5500, () => {
console.log("Server started")
})
【问题讨论】:
-
似乎您没有在
sendFile中使用回调并在文件完全发送之前结束了响应。请查看此处的代码示例:geeksforgeeks.org/express-js-res-sendfile-function 了解如何操作。您需要在回调中调用res.end()
标签: javascript node.js express backend