问题描述
我正在尝试结合Flask和移动Flutter客户端编写rest-api。 我通过Flask-JWT进行身份验证时遇到问题。 我使用ngnix和uwsgi在ubuntu 20.04上运行flask应用程序。 使用flask应用程序的调试模式,它可以毫无问题地运行。
对于Postman来说,它始终有效。 飞镖代码:
Future<String> authRequest() async {
try {
final HttpClient client = HttpClient();
client.badCertificateCallback =
((X509Certificate cert,String host,int port) =>
true); // accept all certificat
final Map login = {
"username": "user","password": "goodsecret",};
final request = await client.postUrl(Uri.parse(ProviderBase.url + '/auth'));
request.headers.add(HttpHeaders.contentTypeHeader,"application/json");
request.add(utf8.encode(json.encode(login)));
final response = await request.close();
final reply = await response.transform(utf8.decoder).join();
final jresponse = json.decode(reply);
ProviderBase.authtoken = jresponse['access_token'];
print('token: ${ProviderBase.authtoken}');
} catch (error) {
print('Error: ${error.toString()}');
}
}
我在扑朔迷离中收到此错误消息(响应):
"<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server Could not understand.</p>"
也许有人有主意? 我现在使用的是自签名证书。
解决方法
我找到了解决方案: 这是缺少的标题内容长度。使用网络服务器是必要的。
这对我有用:
...
final body = utf8.encode(json.encode(login));
request.headers.add(HttpHeaders.contentTypeHeader,"application/json");
request.headers.add(HttpHeaders.contentLengthHeader,body.length.toString());
request.add(body);
...