vue.js 跨域请求 fetch / axios

跨域请求配置

假设我们的请求地址:http://localhost/Graduation_Thesis/a.php

在vue项目下 找到  config  > index.js 文件;修改 index.js 文件下的 proxyTable 对象的内容;如下

    proxyTable: {
      '/api': {              //  '/api'相当于代表  http://localhost/Graduation_Thesis  可自行修改名字
        target: 'http://localhost/Graduation_Thesis', //我们需要请求的主要文件夹地址
        changeOrigin: true, //是否跨域
        pathRewrite: {
          '^/api': '' //路径重写
        }
      }
    },

这样就可以跨域请求  http://localhost/Graduation_Thesis    下的文件了,而需要获取文件下的 a.php 文件 需要用 fetch/  来做请求

fetch  请求

fetch 类似于 ajax 数据提交,但 fetch 更好

参考地址:https://blog.csdn.net/mjzhang1993/article/details/72833095

export default {
  name: 'App',
  components: {
    appHeader:Header
  },
  created(){
    fetch('/api/a.php',{              //  /api既是上面跨域定义的文件地址
      method:"post",                  //请求方式
      headers: {                      //请求头
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body:{                          //发送的请求内容
        username:'hw',
        pass:'123'
      }
    }).then(res => {
      return res.json();
    }).then(res => {
      console.log(res);
    })
  }
}

axios  请求

首先全局安装

npm install axios

在 mian.js 引用

//main.js

import axios from 'axios'


//让 axios 可以全局使用
Vue.prototype.$axios = axios

这样就可以开始使用了

export default {
  name: 'App',
  components: {
    appHeader:Header
  },
  created(){
    this.$axios.post("/api/a.php",{
      username:'hw',
      pass:'1123'
    })
      .then(res =>{
        console.log(res);
      })
  }
}

 

 

 

 

 

 

你可能感兴趣的:(vue.js)