flask vue在同一服务器的解决方案

1、正常安装vue/router/cli等

2、修改frontend/src/router/index.js路由,引入新组件:

import Vue from 'vue'
import Router from 'vue-router'
const routerOptions = [
{ path: '/', component: 'Home' },
{ path: '/about', component: 'About' }
]

const routes = routerOptions.map(route => {
return {
...route,
component: () => import(`@/components/${route.component}.vue`)
}

})

Vue.use(Router)
export default new Router({
routes,
mode: 'history'
})

3、修改前端配置config/index.js

index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
//此处就是修改父级目录

4、构建flask web服务器,主要是制定静态文件和模板文件位置,vue的起始文件为index.html,要用render_template转过去。

from flask import Flask, render_template
app = Flask(__name__,
static_folder = "./dist/static",
template_folder = "./dist")

@app.route('/')
def index():
return render_template("index.html")

5、解决flask路由还是vue路由的问题

我们使用了HTML5的History-Mode在Vue-router需要配置Web服务器的重定向,将所有路径指向index.html。用Flask做起来很容易。将服务端路由修改如下://也就是服务端不再路由:思考如何是部分路由怎么办?

@app.route('/', defaults={'path': ''})
@app.route('/')
def catch_all(path):
return render_template("index.html")

6、使用axios库动态获取后端api

import axios from 'axios'
methods: {
getRandom () {
// this.randomNumber = this.getRandomInt(1, 100)
this.randomNumber = this.getRandomFromBackend()
},
getRandomFromBackend () {
const path = `http://localhost:5000/api/random`
axios.get(path)
.then(response => {
this.randomNumber = response.data.randomNumber
})
.catch(error => {
console.log(error)
})
}
}

7、使用CORS解决跨域访问问题

在后端安装cors即可

cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

另外一种解决方案:

如果应用程序在调试模式下,它只会代理我们的前端服务器。否则(在生产中)只为静态文件服务。所以我们这样做:

import requests
@app.route('/', defaults={'path': ''})
@app.route('/')
def catch_all(path):

if app.debug:

return requests.get('http://localhost:8080/{}'.format(path)).text

return render_template("index.html")

8、解决json字符串转化问题

1)需要在模型类中增加to_json函数:

class Comment(db.Model):
    __tablename__ = 't_comment'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    content = db.Column(db.Text, nullable=False)
    create_time = db.Column(db.DateTime, nullable=False, default=datetime.now)
    author_id = db.Column(db.Integer, db.ForeignKey('t_user.id'))
    question_id = db.Column(db.Integer, db.ForeignKey('t_question.id'))
 
    author = db.relationship('User', backref=db.backref('comments'))
    question = db.relationship('Question', backref=db.backref('comments', order_by=create_time.desc()))
 
    def to_json(self):
        dict = self.__dict__
        if "_sa_instance_state" in dict:
            del dict["_sa_instance_state"]
        return dict

2)将查询的结果,一次通过to_json方法放到数组中,在通过jsonify函数返回到前台:

# rest api接口,并将查询结果转化为json
@app.route('/comments', methods=['GET'])
def comments():
    comments = db.session.query(Comment).all()
    result = []
    for comment in comments:
        result.append(comment.to_json())
    return jsonify(result), 200

参考源码:https://github.com/oleg-agapov/flask-vue-spa

 

你可能感兴趣的:(flask,vue.js,jsonify,tojson)