I'm making a web application that lets users create chatrooms.
This function displays the chatroom messages
@app.route('/enter/<room>')
def enter_chat_room(room):
r = Room.query.filter_by(name=room).first()
return render_template('chatRoom.html', room=r)
This function adds a new message. message.content returns a string with the actual contents of the message object
@app.route('/message/<room>', methods=['POST'])
def post_message(room):
r = Room.query.filter_by(name=room).first()
message = Message(content=request.form['message'], room_id=r.id)
db.session.add(message)
db.session.commit()
return json.dumps(message.content)
This is chatRoom.html
{% extends 'base.html' %}
{% block body %}
<head>
<script type="text/javascript" src="{{ url_for('static', filename='script.js') }}"></script>
</head>
<h1>{{ room.name }}</h1>
<div class="page">
<ul class="messages" id="list">
{% for m in room.messages %}
<li>{{ m.content }}
{% endfor %}
</ul>
</div>
<form method="post" action="{{ url_for('post_message', room=room.name) }}">
<input type="text" id="message" name="message">
<div class="actions"><input type="button" value="Enter" id="theButton"></div>
</form>
{% endblock %}
This is the script.js file
function setup(){
document.getElementById("theButton").addEventListener("click", sendit);
}
function sendit(){
const message = document.getElementById("message").value;
fetch("/message/<room>", {
method: "POST",
headers: { "Content-type": "application/json" },
body: JSON.stringify({message: "contents"})
})
.then((response) => {
console.log(response.json())
return response.json();
})
.then((result) => {
console.log(result)
updateMessages(result);
})
.catch(() => {
console.log("Error posting your message!");
});
}
function updateMessages(result){
var list = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode(result));
list.appendChild(li);
}
window.addEventListener("load", setup);
The issue I'm getting is that every time I try to post a message I get an error message in the console that says "Failed to load resource: the server responded with a status of 400 (BAD REQUEST)" and one that says "Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0"