Vue(八)发送跨域请求

时间:2021-02-24 03:41:10
使用vue-resource发送跨域请求
axios不支持跨域
  • 1 安装vue-resource并引入
cnpm install vue-resource -S
  • 2 基本用法
使用this.$http发送请求
this.$http.get(url, [options])
this.$http.head(url, [options])
this.$http.delete(url, [options])
this.$http.jsonp(url, [options])
this.$http.post(url, [body], [options])
this.$http.put(url, [body], [options])
this.$http.patch(url, [body], [options]) 
 
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>vue</title> <script src="https://unpkg.com/vue"></script>
<script src="vue-resource/vue-resource.min.js"></script>
<script> window.onload=function(){
let app = new Vue({
el:'.container',
data:{ },
methods:{
sendJSONP(){
//https://sug.so.360.cn/suggest?callback=suggest_so&encodein=utf-8&encodeout=utf-8&format=json&fields=word&word=a
this.$http.jsonp('https://sug.so.360.cn/suggest',{
params:{
word:'a'
}
}).then(response => {
console.log(response.data);
},response =>{
console.log('请求失败');
})
},
sendJSONP2(){
//https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=a&json=1&p=3&sid=1443_25549_21113_20930&req=2&csor=1&cb=jQuery110207073365804113201_1515466757822&_=1515466757826
this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',{
params:{
wd:'a'
},
jsonp:'cb' //百度使用的jsonp的参数名为 cb
}).then(response => {
console.log(response.body);
},response => {
console.log('发送失败');
})
}
}
})
} </script> </head> <body> <div class="container">
<!-- 跨域发送请求 -->
<button v-on:click='sendJSONP'>向360搜索发送JSONP请求</button>
<button v-on:click='sendJSONP2'>向baidu搜索发送JSONP请求</button>
</div> </body> </html>