我目前正在研究一個顯示用戶輸入的 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 檔案中具有“responseArea”ID 的 section 元素中?
此外,還有一個帶有 bcrypt 業務邏輯的單獨檔案,但我不包括它,因為我認為不需要它,它只會增加混亂。如果您確實發現需要它,請隨時詢問。
uj5u.com熱心網友回復:
您可以使用 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
uj5u.com熱心網友回復:
我試試這個
const launchAjax = () => {
fetch('/submit-form',
{ method: 'POST' })
.then(res => res.text())
.then((data) => {
area.textContent = data;
})
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/353503.html
標籤:javascript 节点.js 表达 拿来
