Expected output is 'not detected' but I get 'no error' on get and post. Why?
index.html
{% if error %}
<p>{{ error }}</p>
{% else %}
<p>no error</p>
{% endif %}
main.py
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
print('get')
return render_template('index.html')
elif request.method == 'POST':
print('post')
post_data = request.get_json(force=True)
if post_data['message'] == False:
print('false')
print('not detected')
return render_template('index.html', error='not detected')
edit:
not sure if this is what's causing the errors.
script.js
window.onload = (event) => {
if (!window.ethereum) {
console.log('error - not detected');
fetch(`${window.origin}/`, {
method: 'POST',
headers: {'content-type': 'application/json'},
body: JSON.stringify({
'message': false
})
});
} else {
console.log('detected');
}
};
CodePudding user response:
There's something else wrong. I copied your code exactly and ran
curl.exe --header "Content-Type: application/json" -d '{\"message\":false}' http://localhost:5000
and got
<p>not detected</p>
CodePudding user response:
The problem is with your js code. As I can see, you make fetch
call providing parameters and not providing callback for response processing.
It should be:
fetch(`${window.origin}/`, {
method: 'POST',
headers: {'content-type': 'application/json'},
body: JSON.stringify({
'message': false
})
})
.then((response) => response.json())
.then((data) => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
And in backend it's better to return json
response for api calls instead of html. To do it you can change your code:
from flask import jsonify
...
if post_data['message'] == False:
print('false')
print('not detected')
return jsonify(error='not detected')
Ref: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#uploading_json_data