javascript - 使用 fetch 在 html 元素中呈现快速响应
问题描述
我目前正在开发一个显示用户输入的 bcyrpt 散列值的小节点/快速项目。我可以将散列值显示在服务器的 console.log 中,但是我很难将值注入我为结果指定的前端 div 中。
索引.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bcrypt Input Page</title>
</head>
<body>
<form action="/submit-form" method="POST">
<label for="string"><b>String Input:</b></label>
<br>
<input type="text" name="string" required size="40" id="string">
<input type="submit" value="Hash/Salt it!" id="submit-button">
</form>
<section id="responseArea">
</section>
<script src="/script.js"></script>
</body>
</html>
应用程序.js
var express = require('express');
var app = express()
const path = require('path')
const { hashesString, passwordCheck } = require('./bcryptUtil');
app.use(express.urlencoded({
extended: true
}))
app.use(express.static(path.join(__dirname, 'public')))
app.post('/submit-form', (req, res) => {
const userInput = req.body.string;
hashesString(userInput)
.then((output) => {
console.log(output);
res.send(JSON.stringify(output))
})
.catch(err => console.log(err))
})
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, '/index.html'));
//line 10 suffices, you don't need the next line
//res.sendFile(path.join(__dirname, './public/script.js'))
})
app.listen(3003);
脚本.js
const area = document.getElementById("responseArea")
//area.innerHTML = `<h1> Hello World! </h1>`;
const button = document.getElementById("submit-button");
button.addEventListener("click", launchAjax);
/* const launchAjax = (formData) => {
fetch("/submit-form", {
method: "POST",
body: JSON.stringify(formData)
})
.then(response => response.json())
.then(responseJSON => {
area.innerText = responseJSON;
})
} */
const launchAjax = fetch('/submit-form')
.then((res) => res)
.then((data) => {
area.textContent = data;
})
所以我的问题是,如何使用 fetch 从服务器接收 post 请求发送的响应,并将其呈现在 index.html 文件中 id 为“responseArea”的 section 元素中?
此外,还有一个带有 bcrypt 业务逻辑的单独文件,但我不包括它,因为我认为它没有必要,它只会增加混乱。如果您确实发现需要它,请随时询问。
解决方案
您可以使用 JQuery 创建这样的 POST 请求
$.ajax({
type: "POST",
url: `/route`,
data: { /* as an object */ },
success: function (data) {
console.log(data);
},
error: function (data) {
console.error(data);
},
});
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
添加此标记以使用 JQuery,并在此行之后,引用您要添加先前代码的文件
这不是一个非常标准的方法,但它会正常工作。
注意:JQuery 的脚本标签可能是旧的,所以如果你遇到问题,我建议访问最新的 JQuery URL
推荐阅读
- python - 使用 win32api 在内存对象中打印
- keras - keras 中的 preprocess_input 大大增加了火车的大小
- python - OpenCV使用单色相机将帧扔到输出时得到3张图片而不是1张
- java - 通过 Apache.Camel 连接 FTPS 读取超时
- c# - UWP GridView - 如何在调整大小时保持可见项目(列数更改)
- android - 无法解决:de.hdodenhof:circleimageview:2.4.0
- java - 从 Zip 输入流对象中提取单个文件
- apache-kafka - Kubernetes 上的 Kafka - 客户端无法检索元数据
- javascript - 在 React 的返回块中添加函数
- angular - "no-unused-variable": true 在 VSCode 中不起作用