【问题标题】:Angular Dart - How to create a proxy server for angular dart apps?Angular Dart - 如何为 Angular Dart 应用程序创建代理服务器?
【发布时间】:2017-12-01 05:46:54
【问题描述】:

我想为我的 angular-dart 应用程序创建一个代理服务器,每当我刷新浏览器并且路由与 root 不同时,它会将我重定向到 index.html。例如,如果 url 是:http://localhost:8080/users 并且我点击了刷新按钮,我想被重定向到 http://localhost:8080http://localhost:8080/index.html

此外,能够连接到第三方服务器应用程序将非常有用。换句话说,我想运行pub serve 和在localhost:9000 上运行的第三方服务器(python、php 或 java)

【问题讨论】:

    标签: server angular-dart proxy-server dart-shelf angular-router


    【解决方案1】:

    为此,我们可以使用下一个代码:

    import 'dart:convert';
    import 'dart:io';
    import 'package:shelf/shelf.dart';
    import 'package:shelf/shelf_io.dart';
    import 'package:shelf_proxy/shelf_proxy.dart';
    import 'package:shelf/src/message.dart' show getBody;
    
    main() async {
      _startPubServe();
      var server = await serve(handler, 'localhost', 9080);
      print('Proxying at http://${server.address.host}:${server.port}');
    }
    
    handler(Request request) {
      // redirects all the `api` calls to the third party server
      print('request.url.path: ${request.url.path}');
      if (request.url.path.startsWith('api')) {
        print('proxying to: http://localhost:3333/api');
        return proxyHandler('http://localhost:3333/api')(request);
      }
    
      // redirects all files to default `pub serve` path
      var handler = proxyHandler('http://localhost:8080');
      if (new RegExp(r'\.(css|dart|html|png|ttf|otf|TTF)$').hasMatch(request.url.path)) {
        print('proxyiing to: http://localhost:8080');
        return handler(request);
      }
    
      // redirect all the routes to `index.html`
      print('proxying to: http://localhost:8080/index.html');
      return handler(new Request(
          request.method,
          Uri.parse('http://localhost:8080/index.html'),
          protocolVersion: request.protocolVersion,
          headers: request.headers,
          handlerPath: request.handlerPath,
          body: getBody(request),
          encoding: request.encoding,
          context: request.context));
    }
    
    // starts `pub serve` when running this server
    _startPubServe() async {
      String executable = Platform.isWindows ? 'pub.bat' : 'pub';
      var process = await Process.start(executable, ['serve', '--port', '8080']);
      process.stdout.transform(UTF8.decoder).listen(print);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-10
      • 2015-11-14
      • 2020-02-10
      • 1970-01-01
      • 2019-10-16
      • 1970-01-01
      相关资源
      最近更新 更多