1.什么是同源?

同源策略,是浏览器为了保护用户信息安全的一种安全机制。所谓的同源就是指代通信的两个地址(例如服务端接口地址与浏览器客户端页面地址)之间比较,是否协议、域名(IP)和端口相同。不同源的客户端脚本[javascript]在没有明确授权的情况下,没有权限读写对方信息。

ajax本质上还是javascript,是运行在浏览器中的脚本语言,所以会被受到浏览器的同源策略所限制。

示例:

| 前端地址:`http://www.oldboy.cn/index.html` | 是否同源 | 原因                     |
| ------------------------------------------- | -------- | ------------------------ |
| `http://www.baidu.cn/user/login.html`      | 是       | 协议、域名、端口相同     |
| `http://www.baidu.cn/about.html`           | 是       | 协议、域名、端口相同     |
| `https://www.baidu.cn/user/login.html`     | 否       | 协议不同 ( https和http ) |
| `http:/www.baidu.cn:5000/user/login.html`  | 否       | 端口 不同( 5000和80)     |
| `http://bbs.baidu.cn/user/login.html`      | 否       | 域名不同 ( bbs和www )    |

2.不是同源地址在浏览器中发送请求,服务端响应时会被浏览器拦截并报错:

Access to XMLHttpRequest at 'http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.search.catalogSug&query=%E6%88%91%E7%9A%84%E4%B8%AD%E5%9B%BD%E5%BF%83' from origin 'http://localhost:63342' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 

3.ajax解决跨域跨源问题CORS

CORS是一个W3C标准,全称是"跨域资源共享",它允许浏览器向跨源的后端服务器发出ajax请求,从而克服了AJAX只能同源使用的限制。

后端服务器中响应数据中设置响应头信息返回的。

示例:  在后端服务器django视图中加入以下代码

def data(request):
    info = {'name': '张代', 'age': 18}
    ret = JsonResponse(info)
    # ret['Access-Control-Allow-Origin'] = 'http://127.0.0.1:8000'  #允许该地址的请求正常获取响应数据
    # ret['Access-Control-Allow-Origin'] = 'http://127.0.0.1:8000,http://127.0.0.1:8002'
    ret['Access-Control-Allow-Origin'] = '*' #允许所有地址请求都能拿到数据
    
    return ret

3.axios的简单使用

 通过axios实现数据请求,

vue.js默认没有提供ajax功能的。

所以使用vue的时候,一般都会使用axios的插件来实现ajax与后端服务器的数据交互。

注意,axios本质上就是javascript的ajax封装,所以会被同源策略限制。

 

下载地址:

```
https://unpkg.com/axios@0.18.0/dist/axios.js
https://unpkg.com/axios@0.18.0/dist/axios.min.js

```

axios提供发送请求的常用方法有两个:axios.get() 和 axios.post() 。

增   post

删   delete

改   put

查   get

示例代码:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>todolist</title>

</head>
<body>
	<div id="app">
		<h1>天气预报!!</h1>
		<h1>{{data}}</h1>
	</div>
</body>
<script src="vue.js"></script>
<script src="axios.js"></script>
<script>

	let vm  = new Vue({
		el:'#app',
		data(){
			return {
				data:'',
			}
		},

		created(){
			// axios.get('http://wthrcdn.etouch.cn/weather_mini?city=北京')
			axios.get('http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.search.catalogSug&query=大悲咒')
					.then((res)=>{
						// console.log(res);
						// console.log(this);

						this.data = res.data.data.ganmao;
					}).catch(function (error){

			})


		},


	})



</script>
</html>

 示例代码2

// 发送get请求
    // 参数1: 必填,字符串,请求的数据接口的url地址,例如请求地址:http://www.baidu.com?id=200
    // 参数2:可选,json对象,要提供给数据接口的参数
    // 参数3:可选,json对象,请求头信息
    axios.get('服务器的资源地址',{ // http://www.baidu.com
        params:{
            参数名:'参数值', // id: 200,
        }
    
    }).then(function (response) { // 请求成功以后的回调函数
            console.log("请求成功");
            console.log(response);
    
    }).catch(function (error) {   // 请求失败以后的回调函数
            console.log("请求失败");
            console.log(error.response);
    });

    // 发送post请求,参数和使用和axios.get()一样。
    // 参数1: 必填,字符串,请求的数据接口的url地址
    // 参数2:必填,json对象,要提供给数据接口的参数,如果没有参数,则必须使用{}
    // 参数3:可选,json对象,请求头信息
    axios.post('服务器的资源地址',{
        username: 'xiaoming',
        password: '123456'
    },{
        responseData:"json",
    })
    .then(function (response) { // 请求成功以后的回调函数
      console.log(response);
    })
    .catch(function (error) {   // 请求失败以后的回调函数
      console.log(error);
    });

    
    // b'firstName=Fred&lastName=Flintstone'