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"})

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值