Nodejs + Express 总是返回index.html

3 html javascript node.js express

那么,这是什么,我在这里没看到?

问题是,无论我将什么作为文件放入:

app.get('/', function(req, res){
    res.sendfile(__dirname + "/index2");
});
Run Code Online (Sandbox Code Playgroud)

它似乎总是会回来index.html。截至目前,它说index2.html这确实是一个带有 HTML 页面的合法文件,但每当我运行此服务器并访问localhost:8080它时,它仍然会提供基本的index.htmlnot服务index2.html

另外,更改index.html也会带来更改,因此我认为这不是缓存问题。

但是,如果您按下提交按钮,app.post 将正常工作并将您重定向到 kiitos.html

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

app.use(bodyParser());

app.use(express.static(__dirname + '/'))


app.get('/', function(req, res){



res.sendfile(__dirname + "/index2.html");


});

app.post('/', function(req, res){

    var code = req.body.code;
    console.log(code);


  res.sendFile( __dirname + "/kiitos.html");

});



app.listen(8080);
Run Code Online (Sandbox Code Playgroud)

udi*_*idu 7

您的静态文件夹是提供该index.html文件的文件夹,因为它是您的根文件夹。

尝试public为静态文件(如图像、脚本和 css 文件)创建一个文件夹,并将html文件移动到一个views文件夹中,然后使用:

// save static files like images, scripts and css in `public`...
app.use(express.static(__dirname + '/public'))

app.get('/', function(req, res){

    // save html files in the `views` folder...
    res.sendfile(__dirname + "/views/index2.html");
});


app.post('/', function(req, res){

    var code = req.body.code;
    console.log(code);

    res.sendFile( __dirname + "/views/kiitos.html");
});
Run Code Online (Sandbox Code Playgroud)