Issue
I have been trying for a days that a function created as a module can return the data.
I use flask and in a page I am loading the module in the header.
<script src="{{url_for('static', filename = 'js/modules.js')}}"></script>
In my first attempt in the modules.js file I have this function:
function send_to_backend_old(data){
let coucou = fetch('/toronto', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(function(response) {
response.json().then(function(data_received) {
return data_received;
}).then((data_received)=>{
return data_received;
})
});
return coucou
In the html page within the javascript part when I call the function this data does not arrive.
<button type="button" class="btn btn-primary btn-sm" onclick="pruebas_fetch_to_backend();">fetch módulo</button>
function pruebas_fetch_to_backend(){
let datos_json = {};
datos_json.url_api = '/toronto'
datos_json.test1 = 'valor1'
datos_json.test2 = 'valor2'
console.log("---------------------------------------------")
riri = send_to_backend(datos_json)
console.log("valor de riri: "+JSON.stringify(riri))
console.log("---------------------------------------------")
}
the other test is as follows:
async function send_to_backend(data) {
let apiResponse = await fetch("/toronto", {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
let response = apiResponse.json();
// Since we waited for our API to respond using await
// The response variable will return the response from the API
// And not a promise.
console.log(response);
return Promise.all(response);
}
How can I get the response when I call the function from the javascript code in the html page?
Solution
Functions like fetch(...)
and .json()
are asynchronous functions. These return an object of type Promise. This means that the result of the function is not returned immediately.
With await
the final result can be awaited and can then be used. Functions that use the await keyword must be defined as asynchronous.
async function sendFetchRequest() {
const data = await fetchJSONData({
test1: 'value1',
test2: 'value2'
});
console.log(data);
}
As an alternative to await
, however, a callback function can also be passed to a .then(...)
call. Then a synchronous function can also be used to call an asynchronous function.
In this case, a synchronous function returns a Promise
object resulting from the callback of the asynchronous fetch call. The returned object is then awaited in the above function and dumped after getting the final result.
function fetchJSONData(data) {
return fetch('/echo', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(resp => {
return resp.ok && resp.json()
});
}
In order to catch an error, there is the option of using a try-catch block, as well as the use of a callback within .catch(...)
.
So a simple example would look like this.
JS (static/js/module.js)
function fetchJSONData(data) {
return fetch('/echo', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(resp => {
return resp.ok && resp.json()
});
}
HTML (templates/index.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Index</title>
<script src="{{url_for('static', filename='js/module.js')}}"></script>
</head>
<body>
<button type="button" onclick="sendFetchRequest()">Click me!</button>
<script type="text/javascript">
async function sendFetchRequest() {
const data = await fetchJSONData({
test1: 'value1',
test2: 'value2'
});
console.log(data);
}
</script>
</body>
</html>
Flask (app.py)
from flask import (
Flask,
jsonify,
render_template,
request,
)
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.post('/echo')
def echo():
return jsonify(request.json)
Answered By - Detlef
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.