首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular Dart -如何为angular dart应用程序创建代理服务器?

Angular Dart -如何为angular dart应用程序创建代理服务器?
EN

Stack Overflow用户
提问于 2017-06-28 10:29:12
回答 1查看 408关注 0票数 1

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

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

EN

回答 1

Stack Overflow用户

发布于 2017-06-28 10:29:12

为此,我们可以使用下面的代码:

代码语言:javascript
复制
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);
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44792707

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档