使用请求无法读取python休息中的axios数据
问题描述:
我正在尝试向python后端休息发出JavaScript请求,并且出现无法解析的错误。我试图测试一个listname是否在我通过axios数据传递的request.json对象中,但python无法看到它或引发错误。使用请求无法读取python休息中的axios数据
这里是我的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公司忽略甚至张贴虽然不是抛出一个错误(我猜它不会将其视为表单数据)。
我不知道从哪里去,这里的任何帮助将不胜感激。
编辑:
在我的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
答
我猜你是不是在所有发送的数据,因为根据axios documentation的data
选项“只有适用于请求方法'PUT','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请求体。