首页 > 解决方案 > 使用 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 业务逻辑的单独文件,但我不包括它,因为我认为它没有必要,它只会增加混乱。如果您确实发现需要它,请随时询问。

标签: javascriptnode.jsexpressfetch

解决方案


您可以使用 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


推荐阅读