zoukankan      html  css  js  c++  java
  • axiso基本使用及python接收处理

    安装$ npm install axios

    1.发送get请求:

        axios.get("/api/v1.0/cars?id=132").then(function(res){

          console.log(res)

        }).catch(function(err){

          console.log(err)

        });

    2.发送post请求:

    let params = {

          id:4, ctime:'2019-03-1',name:"奔驰4"

        }

        //'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'

        axios.post('/api/v1.0/cars',params,{

            headers: {

                'Content-Type':'application/json'

              }

          }).then(res=>{

            console.log(res.data)

          },err =>{

            console.log(err)

          })

      },

    使用flask模拟后台提供接口,只需要修改config/index.js     下的配置项

        proxyTable: {

                  '/api':'http://localhost:5000/',

            },

    flask 服务器端接口定义:

    @app.route('/api/v1.0/cars', methods=['GET','POST'])

    def get_cars():

        if request.method == 'POST':

            car = request.get_json() #接受post提交的参数

            cars.append(car)

            print(car)

            return jsonify({'ok':'ok'})

        else:

            id = request.args.get("id") #接受get请求的参数

            if id:

                print("id:", id)

                for item in cars:

                    if id == item.get("id"):

                        return jsonify({'cars': item})

                return jsonify({'cars': "id 为" + id + "的车不存在!"})

            else:

                return jsonify({'cars': cars})

    3.put 请求

        axios.put("/api/v1.0/cars?id=1&name=宝马x").then(function(res){

          console.log(res)

        }).catch(function(err){

          console.log(err)

        });

    flask 服务器端接受put请求处理:

    @app.route('/api/v1.0/cars', methods=['PUT'])

    def put_cars():

        """更新指定id的car的name信息"""

        id = request.args.get("id")

        name = request.args.get("name")

        print(request.args)

        for item in cars:

            if int(id) == item.get("id"):

                item['name'] = name

                return jsonify({'cars': item})

        return jsonify({'cars': "id 为" + id + "的车不存在!"})

    4.delete请求

        axios.delete("/api/v1.0/cars?id=2").then(function(res){

          console.log(res)

        }).catch(function(err){

          console.log(err)

        });

    flask 服务器端接受delete请求处理

    @app.route('/api/v1.0/cars', methods=['DELETE'])

    def delete_cars():

        """删除指定id的car信息"""

        id = request.args.get("id")

        print(request.args)

        for item in cars:

            if int(id) == item.get("id"):

                cars.remove(item)

                return jsonify({'errno': 0, 'errmsg':  "delete ok"})

        return jsonify({'cars': "id 为" + id + "的车不存在!"})

    5.get请求路径作为参数时

        axios.get("/api/v1.0/cars/3").then(function(res){

          console.log(res)

        }).catch(function(err){

          console.log(err)

        });

        flask处理

        @app.route('/api/v1.0/cars/<int:id>', methods=['GET'])

        def get_cars_by_id(id):

            for item in cars:

                if int(id) == item.get("id"):

                    return jsonify({'cars': item})

            return jsonify({'cars': "id 为" + id + "的车不存在!"})

    6.axios文件上传:

    <form>

        <input type="text" value="" v-model="name" placeholder="请输入用户名">

        <input type="text" value="" v-model="age" placeholder="请输入年龄">

        <input type="file" @change="getFile($event)">

        <button @click="submitForm($event)">提交</button>

      </form>

        

    data:function(){

        return{

          name:'',

          age:'',

          file:''

        }

      },

      

        getFile(event) {

                this.file = event.target.files[0];

                console.log(this.file);

              },

        submitForm(event) {

                event.preventDefault();

                let formData = new FormData();

                formData.append('name', this.name);

                formData.append('age', this.age);

                formData.append('file', this.file);

                console.log(formData)

                let config = {

                  headers: {

                    'Content-Type': 'multipart/form-data'

                  }

                }

                axios.post('/api/v1.0/upload', formData, config).then(res=>{

                    console.log(res);  

                }).catch(err=>{

                  console.log(err)

                })

              },

    flask服务器端接受

    @app.route('/api/v1.0/upload', methods=['GET', 'POST'])

    def upload_file():

        upload_time = time.strftime("%Y%m%d%H%M%S", time.localtime())

        name = request.form.get("name")

        age = request.form.get("age")

        print("name:" + name + ",age:" + age)

        f = request.files['file']

        f.save("upload/" + upload_time + f.filename)

        return jsonify({'msg': "ok"})

  • 相关阅读:
    验证数字范围的小插件
    解决EJB懒加载问题
    JS获取按键的代码,Js如何屏蔽用户的按键,Js获取用户按键对应的ASII码(兼容所有浏览器)
    struts2标签之<s:select>
    c#(winform)中自定义ListItem类方便ComboBox和ListBox添加项完全解决
    辞职前须慎重考虑
    怎样把PDF文件在WinForm窗口中显示出来
    加载报表失败
    经典正则表达式 Javascript
    无法生成项目输出组“内容文件来自...
  • 原文地址:https://www.cnblogs.com/jlyuan/p/11517119.html
Copyright © 2011-2022 走看看