Cross domain request interface operation using jsonp in vue

  • 2021-09-11 19:20:31
  • OfStack

Foreword:

Here we are using the third-party plug-in jsonp.

github Website: https://github.com/webmodules/jsonp

1. Installation

npm install jsonp -S

2. Introduce

1. Create a new js file to introduce the original jsonp plug-in, then encapsulate the original plug-in, splice the cross-domain interface parameters, encapsulate the jsonp file, then export goes out, and then import goes out wherever it is used.

1. Create a new jsonp. js file to encapsulate the original jsonp plug-in


//  Introduce primitive jsonp Plug-ins 
import originJsonp from 'jsonp'
/*
  Packaging original jsonp Plug-in, returning promise Object 
 url :   Request address 
 data : Requested json Parameter 
 option : Others json Parameter, by default, you can directly write an empty object 
*/
export default function jsonp (url, data, option) {
 url += (url.indexOf('?') < 0 ? '?' : '&') + param(data)
 return new Promise((resolve, reject) => {
 // originJsonp Parameters in can be described in the preface github View in 
  originJsonp(url, option, (err, data) => {
   if (!err) {
    resolve(data)
   } else {
    reject(err)
   }
  })
 })
}
/*
  Encapsulation url Parameter splicing 
 */
function param (data) {
 let url = ''
 for (var k in data) {
  let value = data[k] !== undefined ? data[k] : ''
  //  Prevent garbled when the parameters are Chinese, and use the string as  URI  Component to code 
  url += `&${k}=${encodeURIComponent(value)}`
 }
 return url ? url.substring(1) : ''
}

3. Use

You can create a new getCurrentCity. js file in the js folder that specifically requests the interface to obtain interface data across domains.


//  Introduce packaged jsonp
import jsonp from 'common/js/jsonp.js'
//  Suppose this is an interface for cross-domain requests of the current city 
export function getCurrentCity () {
 //  Interface address 
 let url = 'https://api.map.baidu.com'
 //  Required parameters 
 let datas = {
  'qt': 'dec',
  'ie': 'utf-8',
  'oue': 1,
  'fromproduct': 'jsapi',
  'res': 'api',
  'ak': 'QWilijLzYd6pCmTrHilAeWjbG41zMiXc'
 }
 return jsonp(url, datas, {})
}

4. Finally, the interface data is fetched from the vue component


import {getCurrentCity} from 'common/apis/getCurrentCity.js'

export default {
 methods:{
  _getCurrentCity () {
   //  You can get the interface data of the current city here 
    getCityCurrent().then((res) => {
     //  Print out the acquired data 
     console.log(res)
    }).catch((err) => {
     console.log(err)
    })
   }
 },
 mounted () {
   this._getCurrentCity()
 }
}

Additional knowledge: Encapsulation of axios and jsonp in Vue

I won't talk too much, let's just look at the code ~


import qs from 'qs'
import axios from 'axios' 
 
 // Interceptor 
axios.interceptors.request.use(function (config) {
  console.log(' Sending a request ...')// Add loading Effect 
  return config;
}, function (error) {
  return Promise.reject(error);
});
 
// Add a response interceptor
axios.interceptors.response.use(function (response) {
  console.log(' The request was successful ...')
  return response;
}, function (error) {
  return Promise.reject(error);
}); 
 
const ajax={
	post:function(url,data={}){
		return new Promise((resolve,reject)=>{
			axios.post(url,qs.stringify(data)).then(function(res){
				resolve(res.data)
			}).catch(function(err){
				reject(err)
			})
		})
	},
	get:function(url,data={}){
		return new Promise((resolve,reject)=>{
			axios.get(url,{params:qs.stringify(data)}).then(function(res){
				resolve(res.data)
			}).catch(function(err){
				reject(err)
			})
		})
	},
}
export default ajax;

In main. js

import ajax from './common/api/index.js'

Vue.prototype.$post=ajax.post Vue.prototype.$get=ajax.get

jsonp


import originJSONP from 'jsonp'
/*
jsonp(url,option,callbackFn)
{name:1,age:20}
www.aaa.com/? 
*/
export default function(url,data,option){
 url+=(url.indexOf('?')<0 ? '?' : '&' )+param(data);
 return new Promise(function(resolve,reject){
 originJSONP(url,option,function(err,res){
  if(!err){
   resolve(res);
  }else{
   reject(err)
  }
  })
 })
}
/*
{name='aa',age=20}
&name=aa&age=20
*/
function param(data){
 let url='';
 for(let key in data){
 let item =data[key]!==undefined ? data[key] : '';
 url+=`&${key}=${encodeURIComponent(item)}`
 }
 return url ? url:'';
 }

Related articles: