vue中跨域请求/本地模拟

欢迎访问我的博客地址 : 博客地址

jsonp跨域

1、安装

npm install jsonp -S

2、引入

一般新建一个js文件来引入原始jsonp插件,然后对原始插件进行封装,对跨域接口参数的拼接,封装好这个jsonp文件后export出去,之后在哪里用到就再在那里import。

新建jsonp.js文件来封装原始jsonp插件

import originJSONP from 'jsonp'

/**
 * 封装jsonp
 * @param {*} url 原始的jsonp第一个参数是url,第二个参数是option,这里为了比较好写参数做了下封装
 * @param {obj} data 参数
 * @param {*} option jsonp的option
 */
export default function jsonp(url, data, option) {
  // 如果url没有?就加一个?拼接
  url += (url.indexOf('?') < 0 ? '?' : '&') + param(data)

  return new Promise((resolve, reject) => {
    // 原始jsonp的三个参数,url、option、回调函数
    originJSONP(url, option, (err, data) => {
      // 类似node的设计,如果err是null,表示成功,data是后端返回的数据
      if (!err) {
        resolve(data)
      } else {
        reject(err)
      }
    })
  })
}

export function param(data) {
  let url = ''
  for (var k in data) {
    let value = data[k] !== undefined ? data[k] : ''
    url += '&' + k + '=' + encodeURIComponent(value)
  }
  return url ? url.substring(1) : ''
}

3、配置参数

创建api文件夹,用于储存api调用的js的config.js

export const commonParams = {
    g_tk: 5381,
    inCharset: 'utf-8',
    outCharset: 'utf-8',
    notice: 0,
    format: 'jsonp'
  }
  
  export const options = {
    param: 'jsonpCallback'
  }
  
  export const ERR_OK = 0

可以在专门请求接口的js文件夹中新建一个getDataLists.js文件来跨域获取接口数据。

// 引入封装好的jsonp
import jsonp from './jsonp.js'
import {commonParams, options} from './config'
// 假设这里为跨域请求当前城市的接口

export function getDataLists() {
  const url = 'https://c.y.qq.com/v8/fcg-bin/fcg_myqq_toplist.fcg'

  
  const data = Object.assign({}, commonParams, {
    uin: 0,
    needNewCode: 1,
    platform: 'h5'
  })

  return jsonp(url, data, options)
}

4.使用

  import {getDataLists} from '.././assets/api/getDataLists.js'
export default{
  methods:{
	  _getDataLists () {
	  	  // 在这里就可以获取到当前城市的接口数据了
	      getDataLists().then((res) => {
	      		//console.log(res)
      })
    	}
	},
	mounted () {
    	this._getDataLists()
  }

——————————————————————————————————
axios跨域访问
1.安装axios

npm install -S axios

2.引入main.js中

import axios from 'axios'

Vue.prototype.$axios = axios
axios.defaults.baseURL = '/api'
axios.defaults.headers.post['Content-Type'] = 'application/json';

关键代码是:Axios.defaults.baseURL = '/api',这样每次发送请求都会带一个/api的前缀。

3.配置
vue-cli3.0配置vue.config.js文件
在module.exports ={}中添加如下

devServer: {
    open: true, //是否自动弹出浏览器页面
    host: "localhost", 
    port: '8081',
    https: false,
    hotOnly: false, 
    proxy: {
        '/api': {
            target: 'https://www.api.com/api', //添加API服务器的地址
            changeOrigin: true,
            pathRewrite: {
                '^/api': ''
            }
        }
    },
}

3.使用

  methods:{
        _get(){
          axios.get('')
          .then((res)=>{
              console.log(res.data)
          })
        }
    },
    mounted(){
      this._get()
    }

axios本地模拟数据

在根目录下新建vue.config.js文件,
添加以下:

const express = require('express')
const app = express()
var www = require('./public/mock/mock.json')	//本地文件的地址

var apiRoutes = express.Router();
app.use('/api', apiRoutes)

module.exports = {
    before(app) {
      app.get('/api/www', (req, res) => {
          res.json({
              errno: 0, 
              data: www
          })
      })
  }
}

使用

  axios.get('/api/www').then((res)=>{
                    console.log(res)
                })
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小钱要努力

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值