如何在Dart/shelf中重定向请求?

rta7y2nd  于 2022-12-15  发布在  其他
关注(0)|答案(2)|浏览(126)

我在Dart中使用shelf来设置一个简单的Web服务器。在下面的示例中,我如何将请求从/重定向到/oauth2callback
我已经找到了this method,但不知何故,我无法编译代码,即使我导入dart:io

import 'dart:io';

import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';
import 'package:shelf_router/shelf_router.dart';

final router = Router()
  ..get('/', rootHandler)
  ..get('/oauth2callback', oauth2callback);

Response rootHandler(Request req) {
  return Response.ok('Hello, World!\n');
}

Response oauth2callback(Request request) {
  return Response.ok('Redirected!\n');

}

void main(List<String> args) async {
  final _handler = Pipeline().addMiddleware(logRequests()).addHandler(router);
  final server = await serve(_handler, '0.0.0.0', 8080);
  print('Server listening on port ${server.port}');
}
gg58donl

gg58donl1#

您可以发送如下302响应:

Response rootHandler(Request request) {
  Map<String,String> headers = {'location':'/oauth2callback'};
  return Response(302,headers:headers);
});
e0uiprwp

e0uiprwp2#

您可以使用标准的工具架方法:

return Response.movedPermanently(newUrl); // generates 301

return Response.found(newUrl); // generates 302

相关问题