1.)我有一個功能,可以根據用戶輸入成功生成隨機詞(如果用戶輸入是10個,網站上會顯示10個隨機詞)。如果我使用 GET request fetch api 獲取單詞,則有一個 json 服務器,如下所示: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.)我想將生成的單詞轉移到我的 .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.) 我覺得非常接近我的目標,因為隨機詞生成器可以工作,如果我手動將值設置為let data變量,我也可以將數據 POST 到 .json 文件中,比如let data = ["test"]. 我不知道如何將生成的隨機單詞發送到我的 .json 文件中。4.) 我的 json 文件:{ "randomwords": [], "words": [ "a", "abandon", "ability", "able", "abortion", "about", "above", "abroad", "absence", "absolute", "absolutely", "absorb", "abuse", "academic", "accept", "access"...(remaining words...)}]4.) 我嘗試按照文檔進行操作。也許我需要使用一些timeout,因為在我使用它們之前首先需要生成隨機詞POST request。我已經為此苦苦掙扎了將近一個星期,但找不到解決方案,我幾乎閱讀了 SO 中的所有相關帖子。每一個幫助將不勝感激。在我的getRandomWords()中返回一個承諾,其中一些timeout可能是一個可行的解決方案?
為什么數據不想使用 nodeJS 出現在我的 .json 文件中?
呼喚遠方
2022-11-03 15:18:31