Frontend: React.js
Backend : Django Rest Framework Python
I'm trying to send data as FormData over a WebSocket using the client.send() method.
The data over the WebSocket is transmitted as a string but FormData cannot be converted into a string as it is a special type of Object
addMessage = () => {
const formData = new FormData();
formData.append("room_id", this.state.currentRoomId);
formData.append("messageBody", this.state.curMessage);
formData.append("sender", this.props.user.name);
formData.append("message_Type", "text");
console.log("message being sent = ", formData);
try {
this.client.send(JSON.stringify({ message: formData }));
} catch (error) {
console.log(error); // catch error
}
};
When I try to stringify the formData it returns an empty Object "{}".
If I send this as an object it works, as the object is stringified and parsed to JSON at the backend ( in python ).But using JSON.stringify() on formData returns {}
I've tried sending it without stringifying, and it gets sent as a string "[Object FormData]"
Sent
this.client.send(formData);
Received
When I stringify it and send it, the rest of the object is stringified but the formData gets sent as { } (as mentioned above that it returns an empty object on JSON.stringify() )
Sent
this.client.send(JSON.stringify({ message: formData }));
Received
Sending As an Object
When sending it as an object using
Sent
const message = {
room_id: this.state.currentRoomId,
sender: this.props.user.name,
messageBody: this.state.curMessage,
message_Type : "text"
}
try {
this.client.send(JSON.stringify({ message: message }));
}
........
Received
it is getting sent perfectly
Reason for using FormData and Not a Simple Object:
Previously, I was just sending text messages but now I'm also uploading an image so for that I need to append the image in formData Object and send over the web server
formData.append("image", this.state.selectedFiles);
Any Idea to how to solve this? Either send the formData object intact over the websocket that only sends data as strings or suggest some way to send the image as a part of Object!