Vue的网络请求

时间:2022-06-26
本文章向大家介绍Vue的网络请求,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Vue的高版本里, 建议使用 axios 发起网络请求

  1. 安装
npm install axios
npm install --save axios vue-axios

2.在入口文件配置

import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
 
Vue.use(VueAxios, axios)

3. 组件里用按钮绑定事件用来发起请求

<template>
    <div>
      <button @click="getRequest">get请求</button>
      <button @click="postRequest">post请求</button>
    </div>
</template>

 methods:{
   getRequest(){}
   postRequest(){}
 }

完整的页面代码:

<template>
    <div>
      <button @click="getRequest">get请求</button>
      <button @click="postRequest">post请求</button>
    </div>
</template>

<script>
  import Vue from 'vue';
  /*
  * Vue的高版本里, 建议使用 axios 发起网络请求
  * */
    export default {
        name: "Communication",
      methods:{
        getRequest(){
          Vue.axios.get('/api/get', {
            params: {
              name:'砂瀑我爱罗',
              hobby:'篮球,唱歌'
            }
          }).then((response) => {
            console.log(response.data)
          }).catch((error)=>{
            console.log("请求错误!",error);
          });
        },
        postRequest(){
          Vue.axios.post('/api/post', {
            firstName: '卡西',
            lastName: '卡'
          },{
            transformRequest:[function (data,headers) {
              //data就是要传递的数据,现在是对象格式,我们需要将其转换为参数字符串格式
              //headers也是对象,用于设置请求头的信息
              headers.post["Content-Type"]="application/x-www-form-urlencoded";
              
              //对data对象进行处理
              //根据参数对象拼接 URL query 字符串
              let allstr = '';
              for (let key in data){
                let str=key+"="+data[key]+"&";
                allstr+=str;
              }
              // 去掉最后一个&字符
              allstr=allstr.slice(0,allstr.length-1);
              console.log(allstr);
              return allstr;
            }]
          }).then(function (response) {
              console.log(response.data);
            }).catch(function (error) {
              console.log(error);
            });
        }
      }
    }
</script>

<style scoped>
  div{
    width: 100%;
    height: 75%;
    background-color: #c4ceff;
  }
</style>

4.创建(server)文件夹,创建js文件连接数据库

记得装模块.

配置: 在config文件夹下的index.js文件做如下配置:

proxyTable: {
      // 配置网络请求的转发代理
      "/api":{
        target: 'http://127.0.0.1:1023',
        changeOrigin: true
      }
    },
let express = require("express");
let bp = require('body-parser');

let app = express();
// app.use(bp.urlencoded({extended:false}));
app.use(bp.json());
app.get('/api/get',function (req,res) {
    console.log(req.query.name,req.query.hobby);
    res.json({name:'卡卡西',hobby:'你好'});
});
app.post('/api/post',function (req,res) {
    console.log(req.body.firstName,req.body.lastName);
    res.send("111");
});


app.listen(1023);