Vue vue-jsonp 跨域

vue-jsonp

● npm 安裝 vue-jsonp

npm install vue-jsonp --save
npm i vue-jsonp

● 用法
靜態函數: Vue.jsonp(url, dataObj, timeout)
在Vue組件中: this.$jsonp(url, dataObj, timeout)

● src/main.js 中添加

import Vue from 'vue'
import VueJsonp from 'vue-jsonp'
Vue.use(VueJsonp)

● 其它組件中基本使用方法【在任意.vue文件中使用】

/* 方式1【在Vue組件中】 */
var param = {
  header: { "content-type": "application/xml" }
  callbackQuery: "callbackParam",
  callbackName: "jsonpCallback"
}
this.$jsonp(`http://api.com:9093/api/v1/sso/token`, param).then(res => {
  console.log(res)
}).catch(err => {
  console.log(err)
})

/* 方式2【在Vue組件中】 */
this.$jsonp(`http://api.com:9093/api/v1/sso/token`, {callbackQuery: "callbackParam", callbackName: "jsonpCallback" }).then((json) => {
  // 返回的jsonp數據不會放這裏,而是在 window.jsonpCallback
  console.log(json)
}).catch(err => {
  console.log(err)
})

/* 方式3【在Vue組件中】 */
methods: {
  handleLogin() {
    this.$jsonp('http://api.com:9093/api/v1/sso/token', { callbackName: 'callback' }).then(res => {
      console.log(res)
    }).catch(err => {
      console.log(err)
    })
  }
}

● 靜態函數【在 src/store/modules/user.js 文件中使用】

import Vue from 'vue'
import { login, logout, getInfo, getSsoToken } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  getSsoToken() {
    return new Promise((resolve, reject) => {
      console.log(`Ln 105 /src/store/modules/user.js `)
      Vue.jsonp('http://api.com:9093/api/v1/sso/token', { callbackName: 'callback' }).then(res => {
        const { data } = res
        console.log(`Ln 108 ${JSON.stringify(res)}`)
        if (!data) {
          reject('Verification failed, please Login again.')
        }
        const { token } = data
        console.log(`Ln 85 ${token}`)
        if (!token || token.length <= 0) {
          console.log(`Ln 113 /src/store/modules/user.js 沒有token`)
          // reject('getSsoToken: token must be a non-null array!')
        }
        resolve(data)
      }).catch(error => {
        console.log(`Ln 125 /src/store/modules/user.js ${error}`)
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}


● 靜態函數【在 src/permission.js 文件中使用】

import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import Vue from 'vue'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  NProgress.start()

  document.title = getPageTitle(to.meta.title)

  const hasToken = getToken()

  /* 【方式1】調用 src/store/modules/user.js 文件中 getSsoToken() 方法 */
  const sso = await store.dispatch('user/getSsoToken')
  console.log(`Ln 87 ${JSON.stringify(sso)}`)
  if (sso.token) {
    console.log(`Ln 89 有 ssotoken`)
  } else {
    console.log(`Ln 91 沒有 ssotoken`)
    // next(`/login?redirect=${to.path}`)
    // window.location.href = `http://jy.management.com:9093/#/login?redirect=${window.location}${to.path}`
  }

  /* 【方式2】直接調用 jsonp */
  Vue.jsonp('http://api.com:9093/api/v1/sso/token', { callbackName: 'callback' }).then(res => {
    console.log(`Ln 100 ${JSON.stringify(res)}`)
  }).catch(err => {
    console.log(err)
  })

  if (whiteList.indexOf(to.path) !== -1) {
    // in the free login whitelist, go directly
    next()
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

● 後臺方法
跨域訪問【注意:只支持get請求,不支持post請求
● JQuery對於Ajax的跨域請求有兩類解決方案,都是隻支持get方式。分別是JQuery的 ajax jsonp格式和jquery.getScript方式。
● 要使用跨源請求發送憑據,客戶端必須設置爲:withCredentials: true
● 後端需要添加一個解決跨域方位的過濾器
API接口

[HttpGet("token")]
public IActionResult GetCookie()
{
    string token = string.Empty;
    HttpContext.Request.Cookies.TryGetValue("center-token", out token);
    LogUtils.GetInstance().Info("Ln 24 " + token);
    var user = new SsoVo { token = token };
    return Ok("callback(" + JsonConvert.SerializeObject(new { code = "200", data = new { token = token, ticket = "1234567890abcd" } }) + ")");
}

[HttpGet("LoginJsonp")]
public IActionResult LoginJsonp()
{
    return Ok("callback(" + JsonConvert.SerializeObject(new { code = "200" }) + ")");
}
 
[HttpGet("GetTicket")]
public IActionResult GetTicket()
{
    HttpContext.Response.Cookies.Append("password", "123456");
    HttpContext.Response.Cookies.Append("time", "abcd");
    return Ok("callback(" + JsonConvert.SerializeObject(new { code = "200", data = new { ticket = "1234567890abcd" } }) + ")");
}
 
[HttpGet("GetTicketNew")]
public IActionResult GetTicketNew()
{
    return Content("jsonpscall(" + JsonConvert.SerializeObject(new { code = "200", data = new { ticket = "1234567890abcd" } }) + ")");
}

*
*
*
*
*
*

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章