我想发出一个简单的发帖请求,但是没有任何反应。
在前端的角度中,http标头是这样制作的:
let header = {
headers: new HttpHeaders({
"Content-Type": "application/json",
user: JSON.stringify(JSON.parse(localStorage.getItem("user")).values)
})
};
在应用Flutter,我试图做类似的事情,但是我正在做的一切都会返回错误500,因为标头不正确
从技术上讲,我需要这样做
final Map< String, String> headers = {
"Content-Type" : "application/json",
"user" : {
"token": "BLABLABLA",
"user_id" : "1"
}
} ;
这必须像角钢的前端一样工作,因为后端是这样完成的
登录完成并正常工作,我们将使用SharedPreferences保存登录信息
这是一个很好的问题。很多人都使用包装库作为基本的http库,但是听起来您只在使用基本的库。我认为问题在于,您正在构建标头,就好像Map<String, dynamic>
它实际需要时一样Map<String, String>
。
根据您的服务器设置,您可能可以使它像这样工作:
final Map< String, String> headers = {
"Content-Type" : "application/json",
"user" : jsonEncode({ // add this function call around your object
"token": "BLABLABLA",
"user_id" : "1"
}),
};
上面使用此方法将创建两个标题:
Content-Type: application/json
user: {"token":"BLABLABLA","user_id":1}
但是,您可能不希望这样做,因为某些服务器不喜欢标头内容中的{}
或""
字符。相反,您可以再做两个变体:
= Base 64方法=
尝试在标头中将json字符串设为base64,然后在服务器端将base64解码:
final Map< String, String> headers = {
"Content-Type" : "application/json",
"user" : stringToBase64.encode( // additionally base64 encode it
jsonEncode({ // add this function call around your object
"token": "BLABLABLA",
"user_id" : "1"
}),
),
};
= URL编码方法=
urlencode应该适用于大多数服务器的标头:
final Map< String, String> headers = {
"Content-Type" : "application/json",
"user" : Uri.encodeQueryComponent( // additionally base64 encode it
jsonEncode({ // add this function call around your object
"token": "BLABLABLA",
"user_id" : "1"
}),
),
};
=建议=
但是,如果您只是尝试使用基本的JWT,则可能希望跳过整个用户参数,并将令牌粘贴为标准Authorization: Bearer TOKEN
格式。这是我从其中一个项目中提取并修改的一个工作示例,正是这个示例:
import 'dart:convert';
import 'package:http/http.dart' as http;
String _getToken() {
return 'MY_BEARER_TOKEN';
}
class BaseNetworking {
Future<http.Response> post(
String url,
Map<String, dynamic> data, {
Map<String, String> headers,
}) async {
final Uri uri = Uri.parse(url);
return await http.post(
uri,
headers: _buildHeaders(
requiresAuth: true,
extra: headers,
),
body: jsonEncode(data),
);
}
/// build the headers for the given request. might include authorization or any number of other headers
Map<String, String> _buildHeaders({
bool requiresAuth = true,
Map<String, String> extra,
}) {
final Map<String, String> headers = <String, String>{
'Accept': 'application/json; charset=utf-8',
'User-Agent': 'AppName (version: 1.0.0)',
};
if (extra is Map<String, String>) {
headers.addAll(extra);
}
if (requiresAuth) {
headers['Authorization'] = 'Bearer ${_getToken()}';
}
return headers;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句