Javascript 无法使用请求读取python rest中的axios数据
我试图向python后端rest发出javascript请求,但遇到无法解决的错误。我试图测试我通过axios数据传递的request.json对象中是否有listname,但python要么看不到它,要么抛出错误 以下是我的python代码:Javascript 无法使用请求读取python rest中的axios数据,javascript,python,json,rest,axios,Javascript,Python,Json,Rest,Axios,我试图向python后端rest发出javascript请求,但遇到无法解决的错误。我试图测试我通过axios数据传递的request.json对象中是否有listname,但python要么看不到它,要么抛出错误 以下是我的python代码: @app.route('/', methods=['GET', 'DELETE', 'POST']) def profits(): if request.method=='GET': if 'listname' in reques
@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)
给我带来麻烦的相关行是如果request.json()中的'listname':
以下是我在前端进行的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
如果我改为在request.json中使用If'listname:
TypeError: argument of type 'NoneType' is not iterable
我也尝试过使用表单变量(ie request.form),但是这些值在axios post中被完全忽略,即使没有抛出错误(我猜它不会将其视为表单数据)
我不知道从这里到哪里去,任何帮助都将不胜感激
编辑:
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
我猜您根本没有发送数据,因为根据
数据
选项“仅适用于请求方法‘PUT’、‘POST’和‘PATCH’”
因此,您必须使用POST请求(并相应地更改服务器代码):
axios({
方法:“post”,
网址:'http://localhost:5000/',
标题:{
“内容类型”:“应用程序/json”
},
数据:{
“listname”:this.ledgername
}
})
。然后((响应)=>{
log('这是python服务器对listname的post请求的响应',response);
})
.catch((错误)=>{
log('这是来自listname的python服务器的post请求的错误',错误);
});
或者将listname
作为GET参数而不是JSON发送到请求体中