无法使用请求

时间:2017-06-14 15:18:59

标签: javascript python json rest axios

我正在尝试向python后端休息发出javascript请求,并且收到我无法解决的错误。我试图测试listname是否在我通过axios数据的request.json对象中,但是python要么看不到它,要么抛出错误。

这是我的python代码:

@app.route('/', methods=['GET', 'DELETE', 'POST'])
def profits():
    if request.method=='GET':
        if 'listname' in request.json():
            print 'inside listname == True!!!'
            conn = psycopg2.connect(database = "profitnloss3", user = "patientplatypus", password = "*************")
            cur = conn.cursor()
            sql = 'SELECT * FROM ledger WHERE listname = %s'
            params = (request.json['listname'])
            cur.execute(sql, params)
            conn.commit()
            data = cur.fetchall()
            conn.close()
            return jsonify(data)
        else:
            print 'inside listname == False!!!'
            conn = psycopg2.connect(database = "profitnloss3", user = "patientplatypus", password = "*******************")
            cur = conn.cursor()
            sql = 'SELECT * FROM ledger'
            cur.execute(sql)
            conn.commit()
            data = cur.fetchall()
            conn.close()
            return jsonify(data)

给我带来麻烦的相关行是if 'listname' in request.json():

这是我在前端制作的axios电话:

axios({
      method: 'get',
      url: 'http://localhost:5000/',
      headers: {
        'Content-type': 'application/json'
        },
      data:{
        'listname': this.ledgername
          }
    })
    .then((response)=>{
      console.log('this is the response from the python server on a get request of listname ', response);
    })
    .catch(error=>{
      console.log('here is the error on a get request from the python server of listname ', error);
    })

我得到的错误是:

TypeError: 'NoneType' object is not callable

如果我改为使用if 'listname' in request.json:

TypeError: argument of type 'NoneType' is not iterable

我也尝试过使用表单变量(即request.form),但是即使没有抛出错误,我也会从axios post中完全忽略这些值(我猜它不会将其视为表单数据)。 / p>

我不知道从哪里开始,任何帮助都会受到赞赏。

编辑:

我的python文件顶部的导入标题是

from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS, cross_origin
import sqlite3
import psycopg2

import os
from os.path import join, dirname
from dotenv import load_dotenv

from models.shared import db
from models.profits import Profit

1 个答案:

答案 0 :(得分:0)

我猜您根本没有发送数据,因为根据axios documentation data选项是“仅适用于请求方法' PUT',&# 39; POST'和' PATCH'“

所以你必须使用POST请求(并相应地更改服务器代码):

axios({
  method: 'post',
  url: 'http://localhost:5000/',
  headers: {
    'Content-type': 'application/json'
  },
  data: {
    'listname': this.ledgername
  }
})
.then((response) => {
  console.log('this is the response from the python server on a post request of listname ', response);
})
.catch((error) => {
  console.log('here is the error on a post request from the python server of listname ', error);
});

或在请求正文中将listname作为GET参数而不是JSON发送。