node.js - 节点 js express-session Set-Cookie on Postman/ 不在 Flutter http 标头中
问题描述
我在尝试使用 express-session 将颤振应用程序与我的 nodejs 后端连接时遇到问题。在邮递员中,响应标头包括一个“Set-Cookie”-Header,但颤振标头带有http.post(...)
do not: headers: {content-length: 113, content-type: application/json; charset=utf-8}
。
我需要一个 cookie 来保持经过身份验证的会话与护照。任何想法如何解决它?
颤振标题:
host: '127.0.0.1:3000', connection: 'keep-alive', 'content-length': '57', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36', 'content-type': 'application/json; charset=utf-8', accept: '*/*', origin: 'http://localhost:51879', 'sec-fetch-site': 'cross-site', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', referer: 'http://localhost:51879/', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7'
邮递员标题:'content-type': 'application/json', accept: '*/*', 'postman-token': '7c79280d-****-****-a985-c01395e50e08', host: 'localhost:3000', 'accept-encoding': 'gzip, deflate, br', connection: 'keep-alive', 'content-length': '66'
解决方案
推荐你使用dio 库进行 HTTP 调用。
import 'package:dio/dio.dart';
class ApiProvider {
Dio _dio;
String aToken = '';
final BaseOptions options = new BaseOptions(
// base url to backend server
baseUrl: 'http://a.b.c.d:port/',
connectTimeout: 15000,
receiveTimeout: 13000,
);
static final ApiProvider _instance = ApiProvider._internal();
factory ApiProvider() => _instance;
ApiProvider._internal() {
_dio = Dio(options);
_dio.interceptors.add(InterceptorsWrapper(
onRequest:(Options options) async {
// to prevent other request enter this interceptor,
// use a new Dio(to avoid dead lock) instance to request token.
_dio.interceptors.requestLock.lock();
// set the cookie to headers
options.headers["cookie"] = aToken;
_dio.interceptors.requestLock.unlock();
return options; // continue
}
));
}
Future login() async {
final request = {
"userName": "",
"password": "",
"token": ""
};
final response = await _dio.post('/login', data: request, options: Options(
followRedirects: false,
validateStatus: (status) { return status < 500; }
));
//get cooking from response
final cookies = response.headers.map['set-cookie'];
if (cookies.isNotEmpty && cookies.length == 2) {
// it depends on how your server sending cookie
aToken = cookies[1].split(';')[0];
}
}
/// if we call this function without cookie then it will throw 500 err.
Future getSomething() async {
final response = await _dio.post('/something');
}
}
推荐阅读
- javascript - 如何使用react js在段落中显示结果
- time-complexity - 为什么n^2 logn + n(logn)^2 = O(n^2(logn)^2)的时间复杂度?
- c# - 一般铸造混乱
- python - 如果 Flask 上不存在表,如何使用 SQLAlchemy 创建表?
- html - “这个”在反应的输入中没有识别到获得价值
- excel - 使用 VBA 在 Excel 中为多个文件打开 ASCII 文件 - 循环在同一个输出文件中运行,而不是下一个文件
- python - 在 Python 中如何使用行值来引用列
- python - 无法在 Python3 中安装 tensorflow 模块
- python - Eclipse上的PyDev,代码分析不起作用,一些代码错误检测不到
- python - 如何在 wxpython 桌面应用程序中使用 ipywidgets?