gpt4 book ai didi

javascript - 创建服务器时发送index.html文件

转载 作者:太空宇宙 更新时间:2023-11-04 00:36:38 24 4
gpt4 key购买 nike

我希望在创建服务器时加载像 index.html 这样的文件。当我使用 Node 执行 server.js 时,我会以文本形式发送响应,如 res.end("text")。但我想要加载 index.html

我尝试在 app.get('/getFile') 中使用 sendFile() 加载它,但是当我在地址栏中输入时,我得到了 text 对于所有 url..甚至对于 localhost:3000/getFile

这是我的 server.js:

    (function(){

var http = require("http");
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var path = require('path');

// app.use(express.static(__dirname));
app.use(bodyParser.json());
app.use(express.static(__dirname+'/views'));

var server = http.createServer(function(request, response) {
response.end("text");

});

server.listen('3000');
console.log("Server is listening");

app.get('/getFile',function(request,response){
// response.end('shi');
response.sendFile(path.join('/index.html'));
})
})();

最佳答案

在代码中更改以下内容:

var server = http.createServer(function(request, response) {
response.end("text");
});

对此:

var server = http.createServer(app);

现在,您可以使用以下代码提供静态 index.html 文件:

app.get('/', function(req, res, next){
// Serve the index.html file in the root directory of the website.
res.sendFile(path.join('/index.html'));
});

我希望这有帮助。如果您有任何疑问,请告诉我。

关于javascript - 创建服务器时发送index.html文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38699493/

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