vue通过axios和后端交互的参考例子:
Post数据到后端地址:/post/instanttest
axios默认发送的数据是Payload格式,服务端收到后用data=request.get\_data()获取,然后用json.loads()处理下;
具体代码如下:
var postdata={cacheip: dataresult,targetip: this.targetip}
一、Vue代码:
this.$axios({
method: 'post',
url:'后端地址:端口/post/instanttest',
data:postdata,
}).then(function (response) {
console.log("response:",response);
})
.catch(function (error) {
console.log("error:",error);
});
二、Flask后端代码:
#接收post请求,先允许跨域的options预请求,然后
@app.route('/post/instanttest', methods=['DELETE', 'OPTIONS'])
def deleteTodo():
headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'DELETE',
'Access-Control-Allow-Headers':'content-type'
}
return make_response((jsonify({'error_code': 0}), 202, headers))
@app.route('/post/<post_name>', methods=['POST'])
def postData(post_name):
if post_name=='instanttest':
data=request.get_data()
data=json.loads(data.decode("utf-8"))
targetip=data['targetip']
cacheip=data['cacheip']
recognize_info = {'cacheip': cacheip,'targetip': targetip}
resp=jsonify(recognize_info)
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp