flutter Dart HttpClientRequest.postUrl()无法按预期工作

gtlvzcf8  于 2023-08-07  发布在  Flutter
关注(0)|答案(1)|浏览(145)

我在我的Express服务器上使用Lucia,这是我的Flutter应用程序的支持。我已经按照文档并在Express中创建了一个注销路由。JavaScript代码按预期工作。

  1. router.post("/signout", async (req, res) => {
  2. const authRequest = auth.handleRequest(req, res);
  3. const session = await authRequest.validate(); // or `authRequest.validateBearerToken()`
  4. console.log(req.headers);
  5. console.log(req.body);
  6. if (!session) {
  7. return res.sendStatus(401);
  8. }
  9. await auth.invalidateSession(session.sessionId);
  10. authRequest.setSession(null);
  11. return res.status(200).json({
  12. status: "success",
  13. message: "User signed out successfully"
  14. });
  15. });

字符串
当我从Dart调用这个端点时,它总是返回401,但是当使用fetch from JS发出相同的请求时,它正确地返回200并注销用户。注意:当我将此端点更改为GET端点时,dart get请求按预期正常工作,端点返回200。我不知道我做错了什么,这是Dart post请求:

  1. Future<HttpClientResponse> _postWithSession(String endpoint,
  2. {Map<String, String>? body}) async {
  3. var cookies = await _getCookies(endpoint);
  4. if (cookies.isEmpty) {
  5. throw Exception("Session cookie not found");
  6. }
  7. var req = await _client.postUrl(Uri.parse(endpoint));
  8. req.cookies.addAll(cookies);
  9. req.headers
  10. .set(HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8");
  11. body != null ? req.write(jsonEncode(body)) : req.write(jsonEncode({}));
  12. var res = await req.close();
  13. await _updateCookies(endpoint, res.cookies);
  14. return res;
  15. }


下面是一个成功的请求应该看起来像cURL:

  1. curl "http://localhost:3000/signout" -X POST -H "Origin: http://localhost:3000" -H "Cookie: auth_session=<session_key>"

hmtdttj4

hmtdttj41#

  1. You can modify version of your _postWithSession function that adds the Origin header:
  2. Future<HttpClientResponse> _postWithSession(String endpoint,
  3. {Map<String, String>? body}) async {
  4. var cookies = await _getCookies(endpoint);
  5. if (cookies.isEmpty) {
  6. throw Exception("Session cookie not found");
  7. }
  8. var req = await _client.postUrl(Uri.parse(endpoint));
  9. req.headers.addAll({
  10. HttpHeaders.contentTypeHeader: "application/json; charset=UTF-8",
  11. HttpHeaders.originHeader: "http://localhost:3000", // Replace with your app's origin
  12. HttpHeaders.cookieHeader: cookies.join("; "), // Join multiple cookies if needed
  13. });
  14. body != null ? req.write(jsonEncode(body)) : req.write(jsonEncode({}));
  15. var res = await req.close();
  16. await _updateCookies(endpoint, res.cookies);
  17. return res;
  18. }
  19. please replace http://localhost:3000 with the correct origin of your Flutter app.

字符串

展开查看全部

相关问题