【发布时间】:2021-08-29 10:37:19
【问题描述】:
我刚刚开始学习 Express 和 Servers。
问题
只是想在对表单发出 POST 请求后将另一个 EJS 页面加载到我的 localhost:4000/ 路径作为响应。
但是,尽管我确实从客户端以表单中的 req.body 中的数据获得了 EJS 页面的响应。我似乎无法在浏览器上加载页面。
有什么想法吗?请帮忙
Express.js Server
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
let path = require('path');
let fs = require('fs');
var urlencodedParser = bodyParser.urlencoded({extended:true});
app.use(express.json());
app.set('view engine', 'ejs');
app.use('/', express.static(__dirname + '/views'));
app.use('/', express.static(__dirname + '/views/partial'));
//Handling the GET request with the render of EJS file "index"
app.get('/', (req, res)=> {
res.render('index');
});
//Handling the POST request from the client, and sending the EJS file "createAccount" as a response
app.post('/', urlencodedParser, (req, res) => {
res.set('cache-control', 'max-age=0; private; no-cache');
res.render('createAccount', {data:req.body}); //
});
app.listen(4000, ()=>{
console.log('Port 4000 has been called');
});
编辑: 我已经包含了我用来在下面发出 POST 请求的 JS 文件。
document.querySelector('#btn').addEventListener('click', Master);
async function Master(){
console.log("Button clicked")
const username = document.querySelector("#username").value;
const password = document.querySelector("#password").value;
let results = {
"username": username,
"password": password
};
console.log(results);
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(results)
};
const post = await fetch('/', options);
};
【问题讨论】:
-
提供index.ejs文件,或者你发送post请求的方式。
-
你好,我已经编辑了我的原始问题以包含我用来发出 POST 请求的 JS 文件!
-
您使用 XHR 请求发送请求,在您手动更新之前,您的浏览器不会更新任何内容。您可以将请求作为普通 HTML 表单提交,或者获取响应并更新您的 UI,例如:
$('#body').html(await post.text()); -
对不起老兄,我对这一切都很陌生,所以希望你不要介意我问。您是否建议我需要在最后包含该行作为 JS 文件的一部分以处理响应并随后更新 UI?
-
const post = await fetch('/', options); $('body').html(await post.text());
标签: javascript express ejs