我的flask
代码如下:
@app.route('/sheets/api',methods=["POST"]) def insert(): if request.get_json(): return "Works!
" else: return "Does not work.
"
当请求是:
POST /sheets/api HTTP/1.1 Host: localhost:10080 Cache-Control: no-cache {'key':'value'}
结果是
.Does not work.
当我添加Content-Type
标题时:
POST /sheets/api HTTP/1.1 Host: localhost:10080 Content-Type: application/json Cache-Control: no-cache {'key':'value'}
我收到400错误.
我究竟做错了什么?
您没有发布有效的JSON.JSON字符串使用双引号:
{"key":"value"}
使用单引号时,字符串无效JSON,并返回400 Bad Request响应.
演示仅实现您的路线的本地Flask服务器:
>>> import requests >>> requests.post('http://localhost:5000/sheets/api', data="{'key':'value'}", headers={'content-type': 'application/json'}).text '\n400 Bad Request \nBad Request
\nThe browser (or proxy) sent a request that this server could not understand.
\n' >>> requests.post('http://localhost:5000/sheets/api', data='{"key":"value"}', headers={'content-type': 'application/json'}).text 'Works!
'