axios

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./node_modules/vue/dist/vue.js"></script>
    <!--http://www.axios-js.com/zh-cn/-->
    <script src="./node_modules/axios/dist/axios.js"></script>
</head>
<body>
<div id="app"></div>

<script>
    Vue.prototype.$axios = axios;
    axios.defaults.baseURL = 'http://127.0.0.1:5000';

    var App = {
        template: `<div>
            <button @click="sendAjax">发送get</button>
            <button @click="sendAjaxPost">发送post</button>
            {{datas}}
        </div>`,
        data: function () {
            return {
                msg: '',
                datas: [],
            }
        },
        methods: {
            sendAjax: function () {
                this.$axios.get('/')
                    .then(function (response) {
                        console.log(response);

                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            sendAjaxPost: function () {
                var params = new URLSearchParams();
                params.append('name', 'hg');
                _this = this;//不使用=>时,this在axios中代表window
                this.$axios.post('/create', params)
                    .then((response) => {
                        console.log(response);
                        console.log(this);//this为window
                        console.log(_this);//_this为Vue
                        // _this.datas = response
                        this.datas = response //推荐使用=>箭头函数

                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            }
        }
    };


    new Vue({
        el: "#app",
        template: '<App />',
        components: {
            App
        }
    })

</script>
</body>
</html>
View Code

flask

from flask import Flask
from flask import request
from flask import Response

import json
# from flask_cors import CORS

app = Flask(__name__)

# CORS(app, supports_credentials=True)

# 默认是get请求
@app.route("/")
def index():
    resp = Response("<h2>首页</h2>")
    resp.headers["Access-Control-Allow-Origin"] = "*"
    return resp


@app.route("/course")
def courses():

    resp = Response(json.dumps({
        "name": 'alex'
    }))
    resp.headers["Access-Control-Allow-Origin"] = "*"

    return resp


@app.route("/create", methods=["post", ])
def create():
    print(request.form.get('name'))

    with open("user.json", "r") as f:
        # 将数据反序列化
        data = json.loads(f.read())

    data.append({"name": request.form.get('name')})

    with open("user.json", "w") as f:
        f.write(json.dumps(data))

    resp = Response(json.dumps(data))

    resp.headers["Access-Control-Allow-Origin"] = "*"
    # resp.headers["Access-Control-Allow-Methods"] = "*"
    # resp.headers['Access-Control-Allow-Origin'] = '*'
    # resp.headers['Access-Control-Allow-Methods'] = 'GET,POST'
    # resp.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'

    return resp



if __name__ == '__main__':
    app.run()
View Code

 

posted @ 2019-08-21 19:08  hougang  阅读(129)  评论(0编辑  收藏  举报