flask和Vue3的前后端数据传输

(一)基于flask,构建一个后端

后端就采用flask的一般构建方法,然后用 flask-restful 构建一个接口,接口返回为json数据。

datas = [{'id': 1, 'name': 'xag', '年龄': 18}, {'id': 2, 'name': 'xingag', 'age': 19}]

class UserView(Resource):
    """
    通过继承 Resource 来实现调用 GET/POST 等动作方法
    """
    def get(self):
        """
        GET 请求
        :return:
        """
        return {'code': 200, 'msg': 'success', 'data': datas}


    def post(self):
        # 参数数据
        json_data = request.get_json()

        # 追加数据到列表中
        new_id = len(datas)+1
        datas.append({'id':new_id,**json_data})

        # 返回新增的最后一条数据
        return {'code': 200, 'msg': 'ok', 'success': datas}

# 接口的url设置为 test
api.add_resource(UserView,'/test')

app.run(debug=True)

执行后,也就在本地有了一个服务端。地址为: http://127.0.0.1:5000

(二)用Vue3+axios在客户端获取数据

我们写了vue的App.vue 组件如下:

<template>
  <div>
    <ul>
      {{ info }}
    </ul>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'MyComponent',
  data() {
    return {
      info: []
    };
  },
  mounted() {
    // 用get请求
      // let url = "/test";
      // axios.get('/api' + url)
      // .then(response => {
      //   console.log(response)
      //   this.info = response.data
      // })
      // .catch( error => {
      //   console.log(error)
      // })
      
    // 用post请求
      let url = "/test";
      axios.post('/api' + url,{
        "a":1,"b":2,"c":"你好"
      })
      .then(response => {
        console.log(response)
        this.info = response.data
      })
      .catch( error => {
        console.log(error)
      })


  }
};
</script>

为了解决跨域请求的问题,还需要在 vue.config.js 文件设置如下:

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    proxy: {
        '/api': {
            target: 'http://127.0.0.1:5000/', //接口域名
            changeOrigin: true,             //是否跨域
            ws: true,                       //是否代理 websockets
            secure: true,                   //是否https接口
            pathRewrite: {                  //路径重置
                '^/api': ''
            }
        }
    }
  }
})

效果

这样基本上就能拿到服务端的数据,也能从客户端提交数据到服务端。

在这里插入图片描述

不过关于跨域请求的理论,也不是太清楚,需要在补充一下知识。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值