简体   繁体   中英

Fetch Api is unable to post things to the server

I had created a chatroom in my website and I had used the default action of a form to post message's data into the server and store it in MongoDB. But, know I am trying to make it live by using fetch instead as the data will go the server without refreshing the page simultaneously. But, after posting the data to the server as JSON, the server is unable to get the data of the post. I am also using the Body Parser to get the data in the req object, but, that too isn't working and it shows that the data is null. Can someone tell me how I can fix this issue?

My 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>

My Client-Side 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)); })

My server.js file:

 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(); }) })

I will check your code your server-side are perfect but I think the problem is client-side are a few issues.

check this link same as your solution

I fixed my problem with a simple line of code. Looks like the client-side code and the server code is all fine. We have also specified headers in the options of the fetch too. The problem was that the server didn't know in which format it could expect data from the client. Thus, adding the following code before the app.post() method will fix this issue.

 app.use(express.json());

Then, you do not even need the npm body-parser dependency to parse the incoming data. The data will be added to the req.body object without any additional middleware or dependency.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM