解决Vue请求 ‘No 'Access-Control-Allow-Origin' header is present on the requested resource’错误

xiaoxiao2021-02-28  125

如果我们用VueResouce直接请求,这样写(以豆瓣api为例):

this.$http.get('https://api.douban.com//v2/movie/top250').then((response) => { this.movie = response.data; console.log(this.movie); });

就会报错:

因为这是一个跨域的请求,不能直接去访问别的后台,这里可以用JSONP解决这个问题,直接改写成:

this.$http.jsonp('https://api.douban.com//v2/movie/top250', {}, { headers: {}, emulateJSON: true }).then((response) => { this.movie = response.data; console.log(this.movie); });

就能够正确返回数据了:

豆瓣默认返回20个数据,你可以通过start=a&count=b来取得你想要的a-b的数据

  

至于想了解什么是jsonp,可以看这位博主的文章,讲的很详细:

http://www.cnblogs.com/dowinning/archive/2012/04/19/json-jsonp-jquery.html

转自:http://www.cnblogs.com/lastnigtic/p/6486331.html

转载请注明原文地址: https://www.6miu.com/read-29100.html

最新回复(0)