Javascript 在post请求后重新加载index.html
我想用express和node.js编写一个非常简单的web应用程序。 该应用程序只有一个带有表单的index.html。发布表单时,node.js服务器应通过将输入值写入txt文件来做出反应。 在浏览器中,应重新加载index.html文件以准备提交下一个表单 除了处理请求后重新加载index.html文件的部分之外,我设法使所有内容都正常工作。 index.html位于“www”文件夹中 最好的方法是什么 这是我的app.js:Javascript 在post请求后重新加载index.html,javascript,node.js,express,Javascript,Node.js,Express,我想用express和node.js编写一个非常简单的web应用程序。 该应用程序只有一个带有表单的index.html。发布表单时,node.js服务器应通过将输入值写入txt文件来做出反应。 在浏览器中,应重新加载index.html文件以准备提交下一个表单 除了处理请求后重新加载index.html文件的部分之外,我设法使所有内容都正常工作。 index.html位于“www”文件夹中 最好的方法是什么 这是我的app.js: var express = require('express'
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.
});
参考资料如下:您如何发布表单?使用此解决方案,“{”重定向“/“}”只是在post请求后作为字符串输出对不起,我的语法不好,是否尝试以下操作:返回res.redirect(“/”);更新了答案,查看参考以了解您可能需要探索的其他选项此处的“return”是不必要的,res.redirect(“/”)是您所需要的。