Python requests.Session()的JavaScript替代方案及会话保持问题
Hey there! The root issue here is super straightforward: your Python requests.Session() automatically handles storing and sending cookies from the server—that’s how your backend recognizes the same conversation via the session_id. But your JavaScript code isn’t managing cookies at all, so every request looks like a brand new user to your server, hence the fresh session_id being generated every time.
Let’s Fix the JavaScript First
You just need to tell your XMLHttpRequest to care about cookies. Update your sendxhr function like this:
function sendxhr(user_input, formatter){ var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://localhost:5000/chat'); // This line makes the browser send/receive cookies with the request xhr.withCredentials = true; xhr.setRequestHeader("Content-Type", "application/json"); xhr.setRequestHeader("user_input", user_input); xhr.onload = function () { var res = JSON.parse(xhr.responseText) console.log(res) formatter(res.text) } xhr.send(); }
Double-Check Your Backend Setup (Assuming Flask)
If you’re using Flask for your API, a couple of config tweaks will make sure cookies work as expected:
- Ensure your session cookie’s
SameSitesetting isn’t blocking it from being sent. Add this to your Flask app setup:app.config['SESSION_COOKIE_SAMESITE'] = 'Lax' - If your frontend runs on a different port (like 8080 vs your backend’s 5000), enable CORS with credentials support. Install
flask-corsand add:from flask_cors import CORS CORS(app, supports_credentials=True)
Optional (But Recommended): Clean Up Your Request Method
Quick best practice note: Using a GET request to send JSON data in the body doesn’t follow HTTP standards. It’s better to switch to a POST request, which is designed for sending data to servers. Here’s how to adjust both ends:
Backend (Flask) Update:
@app.route('/chat', methods=['POST']) def chat(): if 'session_id' not in session: session['session_id'] = chat_utils.id_generator() # Pull user input from the request body instead of headers user_input = request.get_json().get('user_input') # Your chat logic here... return jsonify({'text': your_response_text, 'is_end': False})
Frontend Update:
function sendxhr(user_input, formatter){ var xhr = new XMLHttpRequest(); xhr.open('POST', 'http://localhost:5000/chat'); xhr.withCredentials = true; xhr.setRequestHeader("Content-Type", "application/json"); xhr.onload = function () { var res = JSON.parse(xhr.responseText) console.log(res) formatter(res.text) } // Send user input as JSON in the request body xhr.send(JSON.stringify({user_input: user_input})); }
Once you make these changes, your frontend requests will automatically carry the session cookie your backend sets, so the server will recognize the same user across messages and stop generating new session_ids every time.
内容的提问来源于stack exchange,提问作者Matthew Jackson

