![](/img/trans.png)
[英]How can I set the http RequestHeader for a file load in the $script.js library?
[英]How can I use data from POST request to manipulate the DOM using a script.js file
在发出发布请求后,我想更新我的数据库,然后使用数组来更新 DOM。 不幸的是,我不知道如何将该数据发送到我的 script.js 文件。
这是我到目前为止所拥有的
服务器
let expenseAmount = req.body.expenseAmount;
let expenseType = req.body.expenseType;
console.log(expenseAmount, expenseType);
const currentExpense = new expense({
amount: expenseAmount,
reason: expenseType,
})
expense.insertMany(currentExpense, function (err) {
if (err) {
console.log(err)
} else {
console.log("successfully saved")
}
})
expense.find({}, function (err, expenses) {
expenseArr = expenses;
})
})
脚本
const myButton = document.querySelector(".BUTTON")
transferButton.addEventListener("click", function () {
function fetchData() {
fetch('http://localhost:3000/').then(console.log(data))
}
fetchData();
})
如何访问数据库中的数据,然后使用它来操作 DOM
解决 promise 后,您需要从 fetch 中获取数据。
尽管您的then()
设置不正确,但您在正确的轨道上。 您需要设置一个 function 来获取该数据。 然后参考。
要将您的 then 错误更改为:
fetch('http://localhost:3000/').then(data => console.log(data))
这会返回来自 fetch 的响应,尽管数据在响应中,但它仍然不会为您提供数据。 第二个块描述了如果您的请求包含JSON
有效负载,您需要做什么
fetch('http://localhost:3000/')
.then(response => response.json())
.then(data => console.log(data))
这是一个 url 供您参考: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.