【发布时间】:2020-05-19 17:37:12
【问题描述】:
前端 这将获取名称、年龄、城市,以 JSON 格式将其发送到 localhost:5100/getJson,这是我的后端。
<form>
<div class="form-group">
<label for="text">Name:</label>
<input type="text" class="form-control" id="name" placeholder="Enter name" name="name">
</div>
<div class="form-group">
<label for="text">Age:</label>
<input type="text" class="form-control" id="age" placeholder="Age" name="age">
</div>
<div class="form-group">
<label for="text">City:</label>
<input type="text" class="form-control" id="city" placeholder="Enter city" name="city">
</div>
<button onclick = "MyFunction()" id = "submitButton" type="submit" class="btn btn-default">Submit</button>
<p id = "demo">
</p>
<script>
function MyFunction() {
var name = document.getElementById("name").value
var age = document.getElementById("age").value
var city = document.getElementById("city").value
jsonRequest = {"name":name, "age":age, "city":city}
fetch('http://localhost:5100/acceptJson', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: jsonRequest
}).then(res => res.json())
}
</script>
我的后端是 python 中的烧瓶服务器。
后台
app = Flask(__name__)
@app.route('/acceptJson',methods=['GET', 'POST'])
def acceptJson():
jsonData = request.json
name = jsonData['name']
age = jsonData['age']
city = jsonData['city']
postToDatabase(name,age,city)
return "Succesful"
if __name__ == '__main__':
app.run(host = "localhost", port = 5100)
现在,当我使用 Postman 等软件发出相同的 JSON 发布请求时,它可以正常工作,返回 200 并运行脚本。
但是当我通过代码执行时,它返回 200 并且不运行脚本,所以很明显 javascript 中的 POST 有问题,但我不明白哪里错了。
【问题讨论】:
-
body: JSON.stringify(jsonRequest) -
@Barmar 现在它甚至不再发送没有 200 的请求了嗯
-
您在 DevTools 的 Network 选项卡中看到了什么?
-
它只是在网络选项卡中显示“完成”,控制台为空。
-
如果您查看响应,您会看到什么?
标签: javascript python json flask