Next.js调用Python Flask API传递数据失败求助
问题描述
我在尝试用Next.js应用向Python Flask API传递数据,运行脚本发送Instagram消息时始终失败,收到“Error sending data”错误。但如果在server.py中直接指定数据(比如直接填写收消息的用户,而非使用msg_user变量),功能就能正常运行。我怀疑问题可能出在data.get的用法或请求方式(是否应改用GET),多次调试仍无法解决,寻求技术帮助。
相关代码
Next.js (index.tsx)
import { useState } from 'react'; export default function SendMessage() { const [formData, setFormData] = useState({ user: '', pass1: '', msg_user: '', the_msg: '', }); const [responseMessage, setResponseMessage] = useState(''); const handleChange = (e) => { const { name, value } = e.target; setFormData({ ...formData, [name]: value }); }; const handleSubmit = async (e) => { e.preventDefault(); try { // 向Flask API发送POST请求 const response = await fetch('http://localhost:5000/send-message', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(formData), // 发送表单数据到API }); const data = await response.json(); if (response.ok) { setResponseMessage(data.message); } else { setResponseMessage(`Error: ${data.error}`); } } catch (error) { console.error('Error sending data:', error); setResponseMessage('Error sending data.'); } }; return ( <div> <h1>Send Instagram Message</h1> <form onSubmit={handleSubmit}> <label> 账号用户名: <input type="text" name="user" value={formData.user} onChange={handleChange} /> </label> <label> 密码: <input type="password" name="pass1" value={formData.pass1} onChange={handleChange} /> </label> <label> 收件人用户名: <input type="text" name="msg_user" value={formData.msg_user} onChange={handleChange} /> </label> <label> 消息内容: <textarea name="the_msg" value={formData.the_msg} onChange={handleChange} ></textarea> </label> <button type="submit">发送消息</button> </form> {responseMessage && <p>响应: {responseMessage}</p>} </div> ); }
Flask (server.py)
from flask import Flask, request, jsonify from flask_cors import CORS # 导入CORS from instagrapi import Client app = Flask(__name__) CORS(app, origins='http://localhost:3000') # 允许来自http://localhost:3000的请求 @app.route('/send-message', methods=['POST']) def send_message(): try: # 从POST请求中获取数据 data = request.get_json() user = data.get("user") pass1 = data.get("pass1") msg_user = data.get("msg_user") the_msg = data.get("the_msg") # 初始化Instagram客户端 cl = Client() cl.login(user, pass1) send_to = cl.user_id_from_username(username=msg_user) # 发送私信 cl.direct_send(text=the_msg, user_ids=[send_to]) return jsonify({"message": "消息发送成功!"}) except Exception as e: return jsonify({"error": str(e)}) if __name__ == '__main__': app.run(debug=True)
排查与解决方案
1. 确认请求数据是否正确传递
- 在Flask的
send_message函数开头添加打印语句,查看接收的数据是否完整:print("接收到的数据:", data) print("user:", user, "pass1:", pass1, "msg_user:", msg_user, "the_msg:", the_msg) - 在前端
handleSubmit中添加打印,确认发送的表单数据无误:console.log('发送的表单数据:', formData);
2. 处理空值情况
data.get()如果对应键不存在会返回None,可能导致后续操作失败,添加必填字段校验:
@app.route('/send-message', methods=['POST']) def send_message(): try: data = request.get_json() user = data.get("user") pass1 = data.get("pass1") msg_user = data.get("msg_user") the_msg = data.get("the_msg") # 校验所有字段是否为空 if not all([user, pass1, msg_user, the_msg]): return jsonify({"error": "所有字段均不能为空"}), 400 # 后续代码保持不变 cl = Client() cl.login(user, pass1) send_to = cl.user_id_from_username(username=msg_user) cl.direct_send(text=the_msg, user_ids=[send_to]) return jsonify({"message": "消息发送成功!"}) except Exception as e: return jsonify({"error": str(e)})
3. 获取更详细的错误信息
- 前端优化错误处理,打印API返回的具体错误:
const handleSubmit = async (e) => { e.preventDefault(); try { const response = await fetch('http://localhost:5000/send-message', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(formData), }); const data = await response.json(); console.log('API响应:', data); // 打印完整响应 if (response.ok) { setResponseMessage(data.message); } else { console.error('API错误详情:', data.error); setResponseMessage(`错误: ${data.error}`); } } catch (error) { console.error('请求发送失败:', error); setResponseMessage(`请求发送失败: ${error.message}`); } }; - Flask端在控制台打印详细错误,便于排查:
except Exception as e: print("错误详情:", str(e)) # 在Flask控制台查看具体错误 return jsonify({"error": str(e)})
4. 请求方式无需修改
不需要改用GET请求,POST是正确选择——因为涉及敏感信息(密码),GET会将参数暴露在URL中,存在安全风险。
5. 检查CORS配置
临时放宽CORS限制测试,确认是否是跨域问题:
CORS(app) # 允许所有来源的请求
6. 排查Instagram API相关问题
- 直接写死数据能成功可能是因为
instagrapi保留了之前登录的缓存,使用传入的账号时需要重新验证。可以尝试添加登录成功的确认:cl.login(user, pass1) print("登录成功,用户:", cl.username) # 确认登录状态 - 检查Instagram账号是否开启了二次验证,或者是否被限制了私信功能;
instagrapi可能需要额外处理验证步骤。
内容的提问来源于stack exchange,提问作者ditkii
相关产品推荐
相关产品推荐

