![](/img/trans.png)
[英]Why am I getting a Syntax Error when looping through JSON Objects in an array? How do I extract JSON correctly?
[英]Why am I getting a JSON error and how do I fix it
我正在尝试获取插入名字和姓氏字段的值,然后将其插入我使用 restAPI 运行的 MySQL 数据库后端。 我得到了一些帮助来修复表单,但是当我尝试将输入表单输入表单并将其输入数据库时,我试图找到错误
表代码是这个
<div class="superhero">
<h1>Lets add our first name </h1>
<form action="/add_user" method="post">
<input type = "text" firstname = "firstname">
<h1>Lets add our last name </h1>
<form action="/add_user" method="post">
<input type = "text" lastname = "lastname">
<input type="submit" class="btn btn-primary">
</form>
然后使用此命令将其带入 nodeJS 服务器
app.post('/add_people', function(req, res){
axios.get('http://127.0.0.1:5000/api/adduser')
.then((response)=>{
var restlist = response.data.results;
console.log(restlist);
// Now we will execute the results in the page named thanks
});
});
然后最后它将被带到使用这条路线的 RestAPI
@app.route('/api/adduser', methods = ['POST']) # This is a post method because the user needs to be able to add info
def adding_stuff():
request_data = request.get_json() # Gets the info from the table and converts to JSON format
new_fname = request_data['firstname']
new_lname = request_data['lastname']
conn = create_connection("", "", "", "")
sql = "INSERT INTO restaurantusers (firstname, lastname) VALUES ('%s', '%s');" % (new_fname, new_lname) # This sql statement will then be uploaded to the databse to add a new record
execute_query(conn, sql) # This will execute the query
return 'Post worked'
抱歉,如果我问的内容听起来很复杂。 教授在 class 中走得太快了,我一直试图找出如何做到这一点,但没有运气。
UDATE:我后来按照建议更改了这两项。 路线是
app.post('/add_people', function(req, res){
axios.post('http://127.0.0.1:5000/api/adduser')
.then((response)=>{
var restlist = response.data.results;
console.log(restlist);
// Now we will execute the results in the page named thanks
});
});
现在的表格是
<form action="/add_people" method="post">
<input type = "text" firstname = "firstname">
<h1>Lets add our last name </h1>
<input type = "text" lastname = "lastname">
<input type="submit" class="btn btn-primary">
</form>
我得到的错误是
},
isAxiosError: true,
toJSON: [Function: toJSON]
}
还有这个错误在restAPI window
TypeError: 'NoneType' object is not subscriptable
首先,您需要通过使用<input>
上的value
属性来更新表单和输入以正确接受用户输入,而不是
<input type = "text" firstname = "firstname">
<input type = "text" lastname = "lastname">
做这个
<input type="text" value="firstname">
<input type="text" value="lastname">
这会将值firstname
和lastname
发送到您的 API。 如果您需要动态接受用户输入,则需要使用 javascript 观察输入更改并处理表单提交。 检查输入值属性和Javascript 形式。
要将数据从节点服务器发送到 python 服务器,您需要更新
axios.post('http://127.0.0.1:5000/api/adduser')
至
axios.post('http://127.0.0.1:5000/api/adduser', { first_name: req.body.firstname, last_name: req.body.last_name })
因为这样你就可以将 req.body 中的表单数据传递给你的 python 服务器
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.