Vue开发配置跨域请求

打开Config --> index.js文件

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
		'/api': { // 匹配所有以 '/api'开头的请求路径
		  target: 'http://127.0.0.1:8000', // 代理目标的基础路径
		  changeOrigin: true, // 支持跨域
		  // secure: false, // 如果是https接口,需要配置这个参数
		  pathRewrite: {// 重写路径: 去掉路径中开头的'/api'
		    '^/api': ''
		  }
		}
	},

api -->ajax.js文件

/*
ajax请求函数模块
返回值: promise对象(异步返回的数据是: response.data)
 */
import axios from 'axios'
export default function ajax (url, data={}, type='GET') {
  url="/api"+url ///api是Config --> index.js文件里配置的路径
  return new Promise(function (resolve, reject) {
    // 执行异步ajax请求
    let promise
    if (type === 'GET') {
      // 准备url query参数数据
      let dataStr = '' //数据拼接字符串
      Object.keys(data).forEach(key => {
        dataStr += key + '=' + data[key] + '&'
      })
      if (dataStr !== '') {
        dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
        url = url + '?' + dataStr
      }
      // 发送get请求
      promise = axios.get(url)
    } else {
      // 发送post请求
      promise = axios.post(url, data)
    }
    promise.then(function (response) {
      // 成功了调用resolve()
      resolve(response.data)
    }).catch(function (error) {
      //失败了调用reject()
      reject(error)
    })
  })
}

/*
const response = await ajax()
const result = response.data

const resule = await ajax()
 */

1 vue前端结局跨域主要思想是代理功能,比如:
          vue项目:http://localhost:8080/
          后端项目:http://127.0.0.1:8000/

2.在浏览器端访问 http://localhost:8080/api/index/ 路径时,vue会匹配到以 /api/ 开头的请求

3.此时 vue会使用代理功能 自动转发到 http://127.0.0.1:8000/index/ 此时就是同一个域,就不会触发跨域问题

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值