簡體   English   中英

Fetch Api 無法將內容發布到服務器

[英]Fetch Api is unable to post things to the server

我在我的網站上創建了一個聊天室,並使用表單的默認操作將消息數據發布到服務器並將其存儲在 MongoDB 中。 但是,知道我正在嘗試通過使用 fetch 來實現它,因為數據將發送到服務器而不會同時刷新頁面。 但是,在將數據以 JSON 格式發布到服務器后,服務器無法獲取該帖子的數據。 我也在使用 Body Parser 來獲取 req 對象中的數據,但是,這也不起作用,它顯示數據為空。 有人可以告訴我如何解決這個問題嗎?

我的 HTML:

 <form id="form-container"> <input type="text" id="user-name-input" name="userName"> <input required type="text" id="message-input" name="message" placeholder="Send a message here!"> <button type="submit" id="submit-button">Submit</button> </form>

我的客戶端 Javascript:

 submitButton.addEventListener('click', (e) => { e.preventDefault(); var message = document.getElementById('message-input').value; fetch('/dps/chat/request-message-insert', { method: 'POST', body: JSON.stringify({ userName: userName, message: message }), headers: { 'Content-Type': "application/json; charset=UTF-8" } }).then(res => res.json()).then(data => console.log(data)); })

我的 server.js 文件:

 app.post('/dps/chat/request-message-insert', urlencodedParser, (req, res) => { console.log(req.body) const userName = req.body.userName; const message = req.body.message; client.connect(async (err) => { const collection = client.db("gradilo").collection("chat-messages"); await collection.insertOne({ text: message, userName: userName }) await client.close(); }) })

我會檢查你的代碼你的服務器端是否完美,但我認為問題是客戶端有一些問題。

檢查此鏈接與您的解決方案相同

我用一行簡單的代碼解決了我的問題。 看起來客戶端代碼和服務器代碼都很好。 我們還在 fetch 的選項中指定了標題。 問題是服務器不知道它可以從客戶端獲取數據的格式。 因此,在 app.post() 方法之前添加以下代碼將解決此問題。

 app.use(express.json());

然后,您甚至不需要 npm body-parser 依賴項來解析傳入的數據。 數據將被添加到 req.body 對象中,無需任何額外的中間件或依賴項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM