Vue 必备小知识-- 数据请求跨域处理(Cors 和Proxy代理)

1,582 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

本文已参与「掘力星计划」,赢取创作大礼包,挑战创作激励金。

今天来学习 Vue 项目前后端交互, 请求数据是的跨域等问题的两种解决方案.

真机测试:

config/index.js

dev:{host:'0.0.0.0'}

cnpm i axios --save

跨域

<第一种> Cors 方式跨域

通过设置请求头 Access-Control-Allow-Origin'*', 允许各请求来访问.

res.setHeader('Access-Control-Allow-Origin', '*')
const dogModel = require('../model/dogModel')
const url = require('url')
const getDogs = (req, res) => {
  res.setHeader('Access-Control-Allow-Origin', '*')
  dogModel.showCats((data) => {
    res.json(data)
  })
}

module.exports = {
  getDogs,
}

页面请求数据

向后端请求数据, 工作中常用的就是 axios 请求库, 已经封装好了, 我们稍加修改即可使用. 用的比较多的!

<template>
  <div class="hello">
    <input type="text" v-model="dogname" @keyup.enter="add" />
    <button @click="find">查找</button>
    <ul>
      <li v-for="dog in dogs" :key="dog.id">
        {{ dog.name }} {{ dog.age }} <button @click="del(dog.id)">删除</button>
      </li>
    </ul>
  </div>
</template>
<script>
import axios from 'axios'
export default {
  name: 'testApiWithCores',
  data() {
    return {
      dogs: [],
      dogname: '',
    }
  },
  created() {
    this.getData()
  },
  methods: {
    getData() {
      axios.get('http://localhost:3000/dogs').then((res) => {
        this.dogs = res.data
      })
    },
    find() {
      axios
        .get('http://localhost:3000/dogs', {
          params: {
            name_like: this.dogname,
          },
        })
        .then((res) => {
          this.dogs = res.data
        })
    },
    add() {
      axios
        .post(
          'http://localhost:3000/dogs',
          {
            name: this.dogname,
            age: 1,
          },
          {
            headers: {
              'Content-Type': 'application/json',
            },
          }
        )
        .then(() => {
          this.getData()
        })
      this.dogname = ''
    },
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

2 <第二种> http-proxy-middleware 代理

我们的项目一般使用脚手架初始化搭建, 使用 http-proxy-middleware 代理解决

  1. 例如请求的 url: “http://localhost:3000/dogs"

    (需要安装 axios cnpm i axios --save )

  2. 打开 config/index.js,在 proxyTable 中添写如下代码:

// 格式:  用代理的方式跨域
"字符串":{
    target:"目标",
    changeorigin:true,
    pathRewrite:""
}
proxyTable: {
    '/api': { // 使用 '/api' 开头来代替 'http://localhost:9000',
        target: 'http://localhost:9000', // 源地址 设置你调用的接口域名或端口号
        changeorigin: true, // 改变源 跨域
        pathRewrite: {
            '^/api': '' // 路径重写(代替), 这里理解成用 '/api' 代替 target 里面的地址
        }
    }
}

在项目中写请求函数时, 直接

axios.get('/api/dogs').then((res) => {
  this.dogs = res.data
})