• axios 代理服务器转发 get post


    前端使用 vue2 版本 ,后端使用django

    查看已安装的包
    npm list --depth=0

    ├── @babel/core@7.18.10
    ├── @babel/eslint-parser@7.18.9
    ├── @vue/cli-plugin-babel@5.0.8
    ├── @vue/cli-plugin-eslint@5.0.8
    ├── @vue/cli-service@5.0.8
    ├── ant-design-vue@1.7.8
    ├── axios@0.27.2
    ├── core-js@3.24.1
    ├── echarts@4.9.0
    ├── eslint-plugin-vue@8.7.1
    ├── eslint@7.32.0
    ├── v-charts@1.19.0
    ├── vue-router@3.5.4
    ├── vue-template-compiler@2.7.8
    └── vue@2.7.8

    安装 axios

    npm i axios

    服务器

    将服务器开在80端口
    python manage.py runserver 80

    Django version 3.2.5, using settings ‘mysite.settings’
    Starting development server at http://127.0.0.1:80/

    @csrf_exempt导包

    from django.views.decorators.csrf import csrf_exempt
    
    • 1
    • 在后端处理post请求的函数的上一行添加@csrf_exempt
    • 后端处理的代码
    import simplejson
    
    if request.method == "POST":
            data = simplejson.loads(request.body)
            return JsonResponse(data)
    
    • 1
    • 2
    • 3
    • 4
    • 5

    前端代码

    vue.config.js

    代理服务器配置

    const { defineConfig } = require('@vue/cli-service')
    module.exports = defineConfig({
      transpileDependencies: true,
      devServer: {
        proxy: {
          '/jango': {
            target: 'http://localhost:80',
            pathRewrite: { '^/jango': '' },
            // ws: true, //用于支持websocket
            // changeOrigin: true //用于控制请求头中的host值
          },
          // 支持向多个服务器发送请求
          '/demo': {
            target: 'http://localhost:5001',
            pathRewrite: { '^/demo': '' },
            // ws: true, //用于支持websocket
            // changeOrigin: true //用于控制请求头中的host值
          }
        }
      }
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    ^/jango : 只有 jango 开头的 url 链接,才经过代理服务器转发。

    target: 'http://localhost:80', 写对方服务器的 ip 和 端口。

    pathRewrite: { '^/jango': '' }, 代理服务器在转发时,''空字符替换jango

    http://localhost:8080/jango/xxx
    ==>
    http://localhost:80/xxx

    get 请求

    export default {
      data() {
        return { };
      },
      methods: {
        getXXX() {
          axios.get("http://localhost:8080/jango/xxx").then(
            (response) => {
              console.log("请求成功了", response.data);
            },
            (error) => {
              console.log("请求失败了", error.message);
            }
          );
        },
     }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    【注意】
    axios.get("http://localhost:8080/jango/xxx"), 这里是向代理服务器请求,这里填写代理服务器的 ip 和端口。代理服务器的ip是localhost,端口是vue所在的那个端口。

    由于axios是异步的,为了使得axios在某个事件后执行,可使用计时器(延时参数也可以不填),将axios事件推到队尾。

    axios.get("http://localhost:8080/api/query").then(
        (response) => {
            console.log("请求成功了", response.data);
            console.log(this.info);
            this.info = response.data;
            setTimeout(() => {
                this.$emit("back", 1, 1, this.$refs.ali.innerText)
            });
        },
        (error) => {
            console.log("请求失败了", error.message);
        }
    );
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    POST

    postData() {
          axios({
            url: "http://localhost:8080/jango/print/post",
            method: "post",
            //发送格式为json
            data: JSON.stringify({ name: "jie", age: 18 }),
            // data: { name: "jiejie", age: 18 },
          }).then(
            (response) => {
              console.log("请求成功了", response.data);
            },
            (error) => {
              console.log("请求失败了", error.message);
            }
          );
        },
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    在浏览器的网络监视中发现,后端把前端发出去的参数返回来时是如下格式:
    {"name":"jie","age":18}: "",但我们希望它返回的是 {"name":"jie","age":18}

    注意这不是前端的问题,

    后端正确的处理POST传参的方式

    if request.method == "POST":
            data = simplejson.loads(request.body)
            return JsonResponse(data)
    
    • 1
    • 2
    • 3

    以下是错误的方式:
    ×

    if request.method == "POST":
            data = request.POST
            return JsonResponse(data)
    
    • 1
    • 2
    • 3
  • 相关阅读:
    贴近摄影测量,如何让平遥古城焕发生机?
    Qt文件 I/O 操作
    【经验之谈】关于维修电子设备的几点建议和经验
    2012年认证杯SPSSPRO杯数学建模B题(第一阶段)减缓热岛效应全过程文档及程序
    SpringBoot打包的两种方式 - jar方式 和 war 方式
    【不存在的人】用Python获取生成随机头像,还不侵权
    Docker安装Redis——下载Redis镜像——创建配置文件——创建容器实例并启动
    划分成绩ABCD
    python-opencv图像的高通滤波和低通滤波
    [图解]软件开发中的糊涂用语-04-为什么要追究糊涂用语
  • 原文地址:https://blog.csdn.net/sjxgghg/article/details/126413243