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();
})
})
CodePudding user response:
I will check your code your server-side are perfect but I think the problem is client-side are a few issues.
- Check async await because I think responses are not perfect get your DOM through user and Message is perfect work when sending API through post then show a Problem. I will provide the following link to help you
- https://www.topcoder.com/thrive/articles/fetch-api-javascript-how-to-make-get-and-post-requests
check this link same as your solution
CodePudding user response:
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.