Vue中使用jsonp進行跨域請求


Vue-resouse中可以通過this.$http.jsonp的方式直接使用jsonp進行跨域請求。官方在推薦使用axios之后,axios並沒有集成jsonp。但在axios的github中(https://github.com/mzabriskie/axios/blob/master/COOKBOOK.md#jsonp),可以直接安裝jsonp並使用他來坐跨域請求。

<script>

var jsonp = require('jsonp');
export default {
data() {
return {
author: "微信公眾號 jinkey-love",
articles: []
}
},
mounted: function() {
let that = this
jsonp('https://api.douban.com/v2/movie/top250?count=20', null, function (err, data) {
if (err) {
console.error(err.message);
} else {
that.articles=data.subjects
}
});
}
}


</script>

在vue組件中,可以這樣使用,我使用的是豆瓣的一個api接口,但是需要注意的是,jsonp中的函數作用域有變化,因此,需要 在請求之前,let that = this 保存當前的this


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM