呼喚遠(yuǎn)方
2022-11-03 15:18:31
1.)我有一個功能,可以根據(jù)用戶輸入成功生成隨機(jī)詞(如果用戶輸入是10個,網(wǎng)站上會顯示10個隨機(jī)詞)。如果我使用 GET request fetch api 獲取單詞,則有一個 json 服務(wù)器,如下所示:function getRandomWords() { let words = getServerData('http://localhost:3000/words').then(data => { const wordsToMemorize = document.querySelector('#words-to-memorize'); document.querySelector("#wordsInput").addEventListener("click", function() { let temp = wordsToMemorize.value; generatedArrayELements.innerHTML = ""; for(let i = 0; i < temp; i++) { let rander = Math.floor(Math.random() * 3000); generatedArrayELements.innerHTML += data[rander] + "</br>"; }})});}2.)我想將生成的單詞轉(zhuǎn)移到我的 .json 文件中,randomwords array但它不想工作。并且在那里使用 DOM 也沒有意義,我剛剛意識到: function putServerData() { let data = getRandomWords();let fetchOptions = { method: "POST", mode: "cors", cache: "no-cache", headers: { 'Content-Type': 'application/json' }, credentials: "same-origin", body: JSON.stringify(data)};return fetch("http://localhost:3000/randomwords", fetchOptions).then(resp => resp.json()).then(json => console.log(json));}document.querySelector("#wordsInput").addEventListener("click", function() { putServerData();})3.) 我覺得非常接近我的目標(biāo),因為隨機(jī)詞生成器可以工作,如果我手動將值設(shè)置為let data變量,我也可以將數(shù)據(jù) POST 到 .json 文件中,比如let data = ["test"]. 我不知道如何將生成的隨機(jī)單詞發(fā)送到我的 .json 文件中。4.) 我的 json 文件:{ "randomwords": [], "words": [ "a", "abandon", "ability", "able", "abortion", "about", "above", "abroad", "absence", "absolute", "absolutely", "absorb", "abuse", "academic", "accept", "access"...(remaining words...)}]4.) 我嘗試按照文檔進(jìn)行操作。也許我需要使用一些timeout,因為在我使用它們之前首先需要生成隨機(jī)詞POST request。我已經(jīng)為此苦苦掙扎了將近一個星期,但找不到解決方案,我?guī)缀蹰喿x了 SO 中的所有相關(guān)帖子。每一個幫助將不勝感激。在我的getRandomWords()中返回一個承諾,其中一些timeout可能是一個可行的解決方案?
1 回答

慕碼人2483693
TA貢獻(xiàn)1860條經(jīng)驗 獲得超9個贊
您無法通過fetch post調(diào)用將日期添加到 json 文件,但是您可以將數(shù)據(jù)寫入 json 文件,您可以使用 node 來做到這一點(diǎn)fs module。首先制作一個路由處理程序
const fs = require('fs')
router.post("/savedata", (req, res) => {
const jsondata = req.body
fs.writeFileSync('./path/to/your/json/data', jsondata, err => {
if (err) {
res.send("error saving file")
} else {
res.send("data saved successfully")
}
})
})
然后使用 fetch 調(diào)用您在正文中傳遞的數(shù)據(jù)
添加回答
舉報
0/150
提交
取消