You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Flask端点获取数据并通过jQuery发送至另一Flask服务?

解决跨服务AJAX传递JSON数据的问题

看起来你的核心需求是把从8001服务拿到的JSON数据,正确传递给5001服务的/transactions/new端点,这里的关键是让前端发送符合目标服务预期的JSON格式请求体,我来帮你一步步修正:

问题分析

你的目标Flask服务(5001)用request.get_json()来获取数据,这要求请求的Content-Type必须是application/json,并且请求体是JSON字符串。但原代码里直接把从8001拿到的JSON对象传给data,jQuery默认会把它编码成表单格式(key=value),这会导致request.get_json()返回None,进而触发报错。另外还有几个小问题:

  • 前端设置Access-Control-Allow-Origin请求头是无效的,这个是服务器端返回的响应头,用来解决跨域问题,前端不需要加
  • datatype拼写错误,应该是驼峰式的dataType

修正后的前端代码

<script>
function send_response_to_the_server(client_response){
 $.ajax({
 url:"http://127.0.0.1:5001/transactions/new",
 type: "POST",
 dataType: 'json', // 修正拼写错误
 contentType: 'application/json', // 关键:告诉服务器我们发送的是JSON格式数据
 data: JSON.stringify(client_response), // 把JSON对象转换为字符串格式
 success: function(response){
 console.log(response);
 },
 error: function(error){
 console.log(error);
 }
 });
}
$(function() {
 $("#generate_transaction").click(function(){
 $.ajax({
 url:"http://127.0.0.1:8001/new/transaction", // 注意:这里要写完整URL,否则会默认使用当前页面的域名
 type:"POST",
 dataType: 'json',
 data:$('#transaction_form').serialize(),
 success: function(response){
 document.getElementById('Amount').value = ''
 send_response_to_the_server(response);
 },
 error: function(error){
 console.log(error);
 }
 });
 });
});
</script>

额外的跨域处理(如果遇到跨域报错)

如果你的前端页面不是部署在8001或5001服务下,大概率会遇到跨域问题。这时候需要在两个Flask服务中配置CORS:

  1. 先安装扩展:pip install flask-cors
  2. 在8001的Flask服务中添加:
from flask_cors import CORS

app = Flask(__name__)
CORS(app) # 允许所有跨域请求,生产环境可以根据需求配置更严格的规则
  1. 在5001的Flask服务中同样添加:
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

目标服务(5001)的小优化

为了避免因为缺少字段导致报错,可以加个简单的参数校验:

@app.route('/transactions/new', methods=['GET','POST'])
def new_transaction():
 values = request.get_json()
 if not values or 'Amount' not in values:
     return jsonify({'error': 'Missing required fields'}), 400
 value = values['Amount']
 print(value)
 response = {
 'Transaction Amount':"HI"
 }
 return jsonify(response) # 尽量返回JSON格式响应,而非纯文本

这样调整后,点击按钮就能顺利把8001返回的Amount和Signature数据以JSON格式发送给5001服务了。

内容的提问来源于stack exchange,提问作者DevUm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 19:33:08