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

原文地址:https://www.cnblogs.com/jlyuan/p/11517119.html

时间: 2024-08-25 12:10:22

axiso发送网络请求及python接收处理的相关文章

IOS发送网络请求 心得

路线: 实例化URL (网络资源) 利用 URL 建立URLReques (网络请求) 默认是get 请求 对于post 请求 需要创建请求数据体          利用 URLConnection 发送网络请求 (建立连接) 获得结果 或者: (也就是:) URL Reques Connection  HTTP   中利用  URLReques 建立网络请求方式:  GET & POST              get 请求 是 从服务器中取            post 请求 是 往服务

在安卓主线程不能发送网络请求的解决办法

第一种方法: 在主线程中加入这段代码,强制在主线程执行网络请求 if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } 第二种方法: 利用安卓系统自带的异步执行,将网络请求的代码加入在里面 new Async

python发送网络请求

1.使用urllib模块 get请求: res = urlopen(url) from urllib.request import urlopen url = 'http://www.nnzhp.cn' print(urlopen(url))#返回http.client.HTTPResponse object at 0x00000235BA25A160 print(urlopen(url).read().decode())#返回get到的页面的源代码 # decode是将base类型转为enco

Hbuilder MUI里面使用java.net.URL发送网络请求,操作cookie

1. 引入所需网络请求类: var URL = plus.android.importClass("java.net.URL"); var URLConnection = plus.android.importClass("java.net.URLConnection"); var BufferedReader = plus.android.importClass("java.io.BufferedReader"); var InputStrea

go tcp发送网络请求

//发送http请求 package main import ( "fmt" "net" "io" ) func main () { //使用Dial建立连接 conn, err := net.Dial("tcp", "www.baidu.com:80") if err != nil { fmt.Println("error dialing", err.Error()) return }

[小程序]微信小程序获取input并发送网络请求

1. 获取输入框数据wxml中的input上增加bindinput属性,和方法值在js部分定义与之对应的方法,只要在输入的时候,数据就会绑定调用到该方法,存入data属性变量中 2. 调用get请求发起网络请求调用wx.request发起网络请求 3.调用微信Toast接口展示结果 4.按钮绑定bindtap属性,当按钮点击的时候会调用对应的方法 index.wxml部分 <view class="indexInput"> <input maxlength="

Python 学习之urllib模块---用于发送网络请求,获取数据

1.urllib urllib是Python标准库的一部分,包含urllib.request,urllib.error,urllib.parse,urlli.robotparser四个子模块. (1)urllib.request用法 1)urlopen函数:用于打开一个URL(urlopen返回一个类文件对象,可以像文件一样操作) 例如: import urllib.request web=urllib.request.urlopen('http://www.baidu.com') conten

Python 学习之urllib模块---用于发送网络请求,获取数据(2)

接着上一次的内容. 先说明一下关于split()方法:它通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串(把一个字符串分割成很多字符串组成的list列表) 语法:str.split(str="", num=string.count(str)). 参数:str 分隔符,默认为空格.num 分割次数 返回值:返回分割后的字符串列表 例如:你需要将一个英语句子中的每一个单词拿出来单独处理,就可以将其进行分割. 如:a=' I am a new stude

Python 学习之urllib模块---用于发送网络请求,获取数据(5)

查询城市天气最后一节 需要导入上一节的结果city10.py #!/usr/bin/python# -*- coding: UTF-8 -*-import urllib.requestfrom  city10 import city     #从city10.py里导入city变量名称import json         #json包,loads的用法import traceback cityname=input('你想查询什么城市的天气?\n') citycode=city.get(city