在提交请求后重新加载索引.html



我想用express和node.js编写一个非常简单的Web应用程序。 该应用程序只有一个索引.html带有表单。当表单 ist POST 时,节点.js服务器应该通过将输入值写入 txt 文件来做出反应。 在浏览器中,应重新加载索引.html文件,以准备提交下一个表单。

我设法让一切正常工作,除了处理请求后重新加载索引.html文件的部分。 索引.html位于"www"文件夹中。

最好的方法是什么?

这是我的应用程序.js:

var express = require('express')
var app = express()
const fs = require('fs');
const bodyParser = require('body-parser');
app.use(express.static('www'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('Express app listening at http://%s:%s', host, port)
})
server.on('request', (req, res) => {
if (req.method === 'POST') {
collectRequestData(req, res => {
console.log(res);
});
} 
// Here the index.html should be reloaded
});
//This function only writes the form data to txt-file, I don't know if it is relevant here
function collectRequestData(request, callback) {}

处理帖子后尝试重定向到索引:

server.on('request', (req, res) => {
if (req.method === 'POST') {
collectRequestData(req, res => {
console.log(res);
});
} 
// Here the index.html should be reloaded
res.redirect('/');; --->Redirect to index here.
});

参考资料如下: https://expressjs.com/en/4x/api.html#res.redirect

最新更新