如何通过axios get请求发送参数并在flask中接收?

问题描述 投票:0回答:3

我试图通过 get 请求向后端发送 2 个参数,该请求根据我发送到后端的参数返回一些查询。我正在使用 React.js 前端和 Flask python 后端。

我的获取请求如下所示:

async function getStatsData() {
    const req = axios.get('http://127.0.0.1:5000/stat/', {
        params: {
            user: 0,
            flashcard_id: 1
        },
        headers: {'Access-Control-Allow-Origin': '*', 'X-Requested-With': 'XMLHttpRequest'},
    })
    const res = await req;
    return res.data.results.map((statsItem, index) => {
        return {
            stat1: statsItem.stat1,
            stat2: statsItem.stat2,
            stat3: statsItem.stat3,
            stat4: statsItem.user,
            key: statsItem.key
        }
    })
}

然后我在后端的路线是这样的:

@app.route('/stat/<user>/<flashcard_id>', methods=['GET', 'POST', 'OPTIONS'])
def stats(user, flashcard_id):
  def get_total_percent_correct(user):
    correct = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE guess = answer AND user_id = %s' % user)[0][0]
    total = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE user_id = %s' % user)[0][0]
    try:
        return round(float(correct)/float(total),3)*100
    except:
        print('0')
  
  def get_percent_correct_for_flashcard(user,flashcard_id):
    total = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE user_id = %s AND flashcard_id = %s' % (user, flashcard_id))[0][0]
    correct = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE flashcard_id = %s AND guess = answer AND user_id = %s' % (flashcard_id, user))[0][0]
    try:
        return round(float(correct)/float(total),3)*100
    except:
        print('0')

  def get_stats_for_flashcard(user_id, flashcard_id):
    attempts = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE user_id = %s AND flashcard_id = %s' % (user_id, flashcard_id))[0][0]
    correct = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE flashcard_id = %s AND guess = answer AND user_id = %s' % (flashcard_id, user_id))[0][0]
    missed = attempts - correct
    return attempts, correct, missed
  
  data = [{
    "stat1": get_total_percent_correct(user),
    "stat2": get_percent_correct_for_flashcard(user, flashcard_id),
    'stat3': get_stats_for_flashcard(user, flashcard_id),
    'user': user,
    'key':999
  }]

  return {"response_code" : 200, "results" : data}

当我在浏览器中访问 http://127.0.0.1:5000/stat/0/1 时,统计信息显示正确,但获取请求不起作用,因为它显示 xhr.js:210 GET http: //127.0.0.1:5000/stat/?user=0&flashcard_id=1 404(未找到)。很明显我没有正确发送或接收参数。有谁知道如何解决这个问题?谢谢您的宝贵时间

python reactjs flask axios get
3个回答
1
投票

在后端路由中,您期望 url 中的值作为动态段,但从 axios 中,您将其作为 query sring 发送。

解决方案:

您可以像这样修改 axios 请求,以将值作为动态段发送:

  const user = 0;
  const flashcard_id = 1;
  const req = axios.get(`http://127.0.0.1:5000/stat/${user}/${flashcard_id}`,{
    headers: {'Access-Control-Allow-Origin': '*', 'X-Requested-With': 'XMLHttpRequest'},
})

如果您需要从查询参数接收值,您可以像这样修改烧瓶路由:

from flask import request

@app.route('/stat/', methods=['GET', 'POST', 'OPTIONS'])
def stats():
    user = request.args.get('user')
    flashcard_id = request.args.get('flashcard_id')

0
投票

像这样发送参数:

 const req = axios.get(`http://127.0.0.1:5000/stat/${user}/${flashcard_id}`)

在 Flask 中你会收到这样的参数:

@app.route('/stat/<user>/<flashcard_id>', methods=['GET', 'POST', 'OPTIONS'])
def stats(user, flashcard_id):

0
投票

您也可以尝试:

@app.route('/axios_to_flask',methods=['GET',"POST"])
def register():
  print(request.get_json())
  return jsonify({'message':'here is your responce'})

查看这个指南

© www.soinside.com 2019 - 2024. All rights reserved.