webServer 与 Angular应用 路由问题
当部署单页面应用时,碰到的比较突出的一个问题便是,当我们在地址栏输入指定地址时得不到预期的页面响应。产生的原因便是应用自身路由与webServer的路由出现偏差与冲突。
同样,本人在开发Angular应用时也遇到了这种题。本人使用python的flask框架搭建了一个简单的webServer来部署Angualr应用。下面会贴出关键代码,供大家参考解决问题。
# _*_ conding:UTF-8 _*_
# __init__.py
import os
from flask import Flask, send_from_directory, redirect, url_for
from werkzeug.routing import BaseConverter
# import database create table
from . import dbcreate
class RegexConverter(BaseConverter):
def __init__(self,url_map,*items):
super(RegexConverter,self).__init__(url_map)
self.regex=items[0]
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
# DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
)
if test_config is None:
# load the instance config, if it exists, when not testing
app.config.from_pyfile('config.py', silent=True)
else:
# load the test config if passed in
app.config.from_mapping(test_config)
# ensure the instance folder exists
# try:
# os.makedirs(app.instance_path)
# except OSError:
# pass
# create data table
dbcreate.vmcreate(app)
# import blueprint
from .view import index
from .view import product
from .view import company
from .view import detail
# regex URL
app.url_map.converters['regex'] = RegexConverter
# register blueprint
app.register_blueprint(index.index,url_prefix='/index')
app.register_blueprint(product.product,url_prefix='/product')
app.register_blueprint(company.company,url_prefix='/company')
app.register_blueprint(detail.detail,url_prefix='/detail')
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'),'favicon.ico', mimetype='image/vnd.microsoft.icon')
@app.route('/<regex(".*"):url>')
def user(url):
return redirect(url_for('detail.detail_detail'))
return app
if __name__ == '__main__':
app.run(debug=True)
# _*_ conding:UTF-8 _*_
# detail.py
from flask import Blueprint, render_template, redirect, Response, request
from contextlib import closing
detail = Blueprint('detail',__name__)
@detail.route('/detail/<regex(".*"):url>')
def detail_detail(url):
return render_template('angular.html')
<!-- Angular应用主体页面(flask的蓝天模板) -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MyApp</title>
<base href="/detail/detail">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="/static/angular/favicon.ico">
</head>
<body>
<app-root></app-root>
<script type="text/javascript" src="/static/js/runtime.js"></script>
<script type="text/javascript" src="/static/js/polyfills.js"></script>
<script type="text/javascript" src="/static/js/styles.js"></script>
<script type="text/javascript" src="/static/js/scripts.js"></script>
<script type="text/javascript" src="/static/js/vendor.js"></script>
<script type="text/javascript" src="/static/js/main.js"></script>
</body>
</html>