Kurssin materiaalissa ei tainnut olla suoraa mallia siitä kuinka javascriptin fetchillä lähetetään palvelimelle muuta kuin lomakemuotoista dataa. Tässä pieni lisäesimerkki miten lähetetään esim. json-muotoista dataa:
javascript:
const response = await fetch("https://eur03.safelinks.protection.outlook.com/?url=https%3A%2F%2Ffoobar.exa...", { "method": "POST", "headers": { "Content-Type": "application/json" }, "body": JSON.stringify(data) // data on lähetettävä tieto });
const result = await response.text(); // vastaus voi toki olla //muutakin kuin tekstiä if ( response.status == 200 ) { console.log("onnistui!"); } else { console.log("virhe tuli"); } } catch (error) { console.error("Verkkovirhe"); }
lisäesimerkkejä edellisen kurssin materiaalissa: https://appro.mit.jyu.fi/tiea2120/vt/vt2/2024/vt2-apufunktiot.js
Palvelimella tiedot otetaan vastaan esim. seuraavasti:
@app.route('/flaskinroute', methods=["POST"]) def malli(): try: data = json.loads(request.data) except Exception as e: return Response( str(e), mimetype="text/plain;charset=UTF-8", status=400)
return Response("ok", mimetype="text/plain;charset=UTF-8", status=200)