Сеанс Flask не сохраняется (Postman работает, Javascript — нет)Python

Программы на Python
Гость
Сеанс Flask не сохраняется (Postman работает, Javascript — нет)

Сообщение Гость »


Я разрабатываю сервер Flask для взаимодействия между некоторыми внутренними функциями Python и клиентами Javascript через Интернет. Я пытаюсь использовать Flask variable to store user specific data over the course of their time interacting with the app. I've removed most of the application specific code below but the core problem I'm experiencing remains.

Here is my the code for my (simplified) Flask app:

Код: Выделить всё

import json
import os
from flask import Flask, jsonify, request, session

app = Flask(__name__)
app.secret_key = 'my_secret_key'

@app.route('/', methods=['GET'])
def run():
session['hello'] = 'world'
return jsonify(session['hello'])

@app.route('/update', methods=['POST'])
def update():
return jsonify(session['hello'])

if __name__ == '__main__':
app.run(host='0.0.0.0')
Utilizing Postman, I can make a GET request to my server and receive the expected output of . I can then make a POST request with an arbitrary body and receive the same expected output of (again using Postman).

When using Chrome, I can visit my server IP and see the expected output on the page. I can also manually make a GET request using Javascript (in Chrome's console) and receive the same response as expected. However, my problem arises when trying to send a POST request to the server using Javascript; the server shows a

Код: Выделить всё

KeyError: 'hello'
when trying to make this request.

Here is the Javascript I'm using to make the POST request:

Код: Выделить всё

var url = 'http://my_server_ip/update';
fetch(url, {
method: 'POST',
body: JSON.stringify('arbitrary_string'),
headers: new Headers({
'Content-Type': 'application/json'
})
})
.then(response => response.json())
.then((data) => {
console.log(data);
})
What's going wrong here? Why can I make the GET/POST requests with Postman just fine but run into errors making the same requests with Javascript?


Источник: https://stackoverflow.com/questions/497 ... ipt-doesnt

Вернуться в «Python»