Skip to content

提交作业--邢伟 #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions CORS头部信息和用途.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<!-- 响应头 -->
Access-Control-Allow-Origin: <origin> | *
origin 参数的值指定了允许访问该资源的外域 URI,如果请求不需要身份凭证,可以用星号*,所有域都可以请求


Access-Control-Expose-Headers: X-My-Custom-Header, X-Another-Custom-Header
XMLHttpRequest对象的getResponseHeader可以拿到Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma这些基本头的其他自定义头。

Access-Control-Max-Age
决定预请求到的结果可以缓存多长时间

Access-Control-Allow-Credentials
js的请求中,如果credentials:"include", 则浏览器会根据这个返回字段决定是否要把服务器的respond返回给前端Javascript,
true: 返回;false:不返回

Access-Control-Allow-Methods
跨域允许使用到的方法

Access-Control-Allow-Headers
规定了跨域时允许携带的首部字段。

<!-- 请求头 -->
Origin: <origin>
说明请求发起的来源

Access-Control-Request-Method
实际请求时,需要使用的方法

Access-Control-Request-Headers
实际跨域请求时,会携带的请求头字段
53 changes: 53 additions & 0 deletions http 请求失败后重试的代码.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
const api = {
fetchData() {
return fetch("/source").then(res => {
if (res.ok) return res.json();
});
}
};

class Service {
// 请求次数和请求间隔
static timeGaps = [1, 10, 60];
// 用于记录正在重试的函数和当前函数的时间间隔
static requestMap = {};

// 获取数据
static getResource() {
const funcName = "getResource";

api
.fetchData()
.then(res => {
// handle response data here...

// 数据请求成功,删除requestMap中的key
this.clearRequestMap(funcName);
})
.catch(err => {
// 网络故障,呼叫控制器进行断网重试
this.retryControl(funcName);
});
}

// 请求数据函数的控制函数,控制重试时机
static retryControl(name) {
let index = this.timeGaps.indexOf(this.requestMap[name]);
if (index < this.timeGaps.length - 1) {
index += 1;
this.requestMap[name] = this.timeGaps[index];
setTimeout(() => {
// 重新发送请求,这里暂不考虑传参的问题
this[name]();
}, 1000 * this.timeGaps[index]);
} else {
// 超过请求次数,不再请求
this.clearRequestMap(name);
alert('请检查网络')
}
}

static clearRequestMap(name) {
this.requestMap[name] = undefined;
}
}
3 changes: 3 additions & 0 deletions 一段代码让CORS跨域请求带cookie.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
fetch('https://example.com', {
credentials: 'include'
})
3 changes: 3 additions & 0 deletions 作业要求.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
1、列举 CORS 的头信息,并说明⽤途
2、写⼀段代码让 CORS 跨域请求带上 cookie
3、写⼀段让 http 请求失败后重试的代码