1.客户端与服务端交互(跨域问题解决)
1.1跨域的介绍与报错
错误:blocked by CORS policy: No 'Access-Control-Allow-Origin'
跨域 , 浏览器同源禁止策略
浏览器要求:只有同源的客户端和服务器才可以互相使用ajax进行交互
同源:域名 协议 端口 完全相同
1.2跨域的解决
如何解决跨域:
1)服务器允许跨域
2)中转服务器
搭建服务器,从服务器向对方服务器发起请求,将数据传递给客户端
3)JSONP技术
优点:简单方便,,利用script标签的src属性,完成跨域
缺点:并非所有服务器都是支持jsonp
暂时学了JSONP技术
2.JSONP技术引用
运用src引用 与 回调函数 获取返回结果
//获取海贼王
<script src="http://cache.video.iqiyi.com/jp/avlist/202861101/${page}/?callback=fn"></script>
//回调函数 接受jsonp技术访问对方服务器后传递回的数据
function fn(data){
console.log(data)
}
3.jquery与ajax
3.1 get
jQuery.get(url, [data], [callback], [type])
url:待载入页面的URL地址
data:待发送 Key/value 参数。
callback:载入成功时回调函数。
type:返回内容格式,xml, html, script, json, text, _default。
// $.get('http://localhost:4000',{name:'java'},function(data){
// console.log(data)
// },'json')
3.2 post
jQuery.post(url, [data], [callback], [type])
// $.post('http://localhost:3000',{username:'admin',password:'123'},function(data){
// console.log(data)
// },'json')
3.3 jQuery.ajax(url,[settings]) get与post均可使用
//get post均可用的方法
$.ajax({
type : 'POST',//登录方式
url : 'http://localhost:3000',//域名地址
data : 'username=admin&password=12',//传递参数
success:function(data){//成功 获取返回值
console.log(data)
},
error:function(err){//失败 返回原因
console.log(err)
},
})
4.fetch()
该方法提供了一种简单,合理的方式来跨网络异步获取资源。需要两个then()
4.1 get
默认传输方式为get 用此方法get传输参数,需要在url上传输 ,不能够使用body .
// fetch("http://localhost:4000?name=java(参数的传递)")).then(function(res){
// return res.text(); //若后台返回值为文本类型(具体看需要)
// return res.json(); //若返回值为json字符串
// }).then(function(data){
// console.log(data)
// })
4.2 post
fetch("http://localhost:3000",{
method:'POST',//类型
body:'username=admin&password=123'//参数
}).then(function(res){
return res.json(); //若返回值为json字符串
}).then(function(data){
console.log(data)
})
Fetch官网
5.axios
axios官网
5.1 get
get传参用params
//get 无参
// axios.get('http://localhost:4000').then(data=>{
// console.log(data.data)
// })
//get 有参
// axios.get('http://localhost:4000?name=java').then(data=>{
// console.log(data)
// })
axios.get('http://localhost:4000', {
params: {
name: 'java'
}
}).then(data => { //接收成功信息
console.log(data)
}).catch(err => {
console.log(err)//接受失败信息
})
5.2 post
//注意:post方法,第二个参数需要一个字符串
//post 无参
// axios.post('http://localhost:3000').then(data=>{
// console.log(data)
// })
//post有参 //注意:post方法,第二个参数需要一个字符串
axios.post('http://localhost:3000', 'username=admin&password=123').then(data => {
console.log(data)
}).catch(err => {
console.log(err)
})
5.3 axios();
axios({
method:'POST',
url:'http://localhost:3000',//域名
data:'username=admin&password=123',//传递参数
}).then(data=>{
console.log(data)
}).catch(err=>{
console.log(err)
})