anjia / blog

博客,积累与沉淀
107 stars 4 forks source link

网络相关 #38

Open anjia opened 5 years ago

anjia commented 5 years ago

Cookie

document.cookie

前端路由和数据接口,均配置 host

function escapeRe(str) {
    return str.replace(/[.*+?^$|[\](){}\\-]/g, '\\$&');
}

// Get the cookie value by key.
function get(key, decoder = decodeURIComponent) {
    if ((typeof key !== 'string') || !key) {
        return null;
    }

    const reKey = new RegExp(`(?:^|; )${escapeRe(key)}(?:=([^;]*))?(?:;|$)`);
    const match = reKey.exec(document.cookie);
    if (match === null) {
        return null;
    }

    return typeof decoder === 'function' ? decoder(match[1]) : match[1];
}

export default {
    get: get
}
anjia commented 5 years ago

跨域

报错.1

Access to XMLHttpRequest at 'http://api.test.com' from origin 'http://www.test.com'
has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.

原因:跨域 解决:res.header('Access-Control-Allow-Origin', '*');

报错.2

Access to XMLHttpRequest at 'http://api.test.com' from origin 'http://test.com'
has been blocked by CORS policy:
The value of the 'Access-Control-Allow-Origin' header in the response
must not be the wildcard '*' when the request's credentials mode is 'include'.
The credentials mode of requests initialed by the XMLHttpRequest 
is controlled by the withCredentials attribute.
Access to XMLHttpRequest at 'http://api.test.com' from origin 'http://www.test.com'
has been blocked by CORS policy:
The 'Access-Control-Allow-Origin' header contains multiple values
'http://www.test.com:8888,http://www.test.com:8889',
but only one is allowed.

原因:跨域+凭据 解决:

报错.3

header-2

原因:请求没发送成功 解决:跨域相关、ResponseHeader 的一系列Access-Control-Allow-*

Provisional headers are shown 显示临时 Header 原因较多。eg. 取了缓存-没真正发请求


res.header('Access-Control-Allow-Credentials', 'true');  // 开启凭据/证书。会带上 cookie
res.header('Access-Control-Allow-Origin', origin);  // 开启了凭据,此处需具体的 origin, 且不能多个
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With');
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
anjia commented 5 years ago
anjia commented 5 years ago

POST 提交数据

POST 提交的数据是在消息主体(entity-body)中的。

但是,协议并没有规定数据的编码方式。所以,我们可以自行决定消息主体的格式。

具体用哪种格式,需要和服务器端约定下 毕竟,提交的数据,只有服务器解析成功了,才有意义

一般情况,服务器端语言及他们的 framework,都内置了自动解析常见数据格式的功能。 通常,是根据 Request Header 里的 Content-Type 来得知请求中消息主体的编码方式的。

所以,POST 提交数据的方案,包含了两部分:

application/x-www-form-urlencoded

最常见的,POST 提交数据的方式。

浏览器原生的<form>如果不设置enctype属性,默认就是这种方式

两部分:

Form Data - 解析过的 Form Data - 源格式
post-11 post-12

multipart/form-data

也很常见。

application/json

此时,那两部分:

JSON 规范很流行。

此方式可以很方便地提交复杂的结构化数据,特别适合 RESTful 接口 各大抓包工具都会以树形结构展示 JSON 数据,很友好

text/xml

此时,Form Data 里数据的编码方式是 XML。

相对 JSON,它的结构还是有些臃肿。

当然,我们也可以自定义新的数据格式,来提交


application/x-www-form-urlencoded 和 multipart/form-data 都是浏览器原生支持的。

在现阶段的标准中,原生<form>表单也只支持这两种格式,是通过enctype属性指定的。

当 method 属性是 post 时,enctype指定提交给服务器的 MIME 类型。取值可以是:

anjia commented 5 years ago

axios

// 拦截请求
axios.interceptors.request.use(config => {
    if(config.url == URL.login){
        return config
    }else{
        return new Promise((resolve, reject) => {
            myFunc().then(data => {
                resolve(config)
            }).catch(err => {
                reject(err)
            })
        })
    }
}, error => {
    return Promise.reject(error);
})

// 拦截响应
axios.interceptors.response.use( response => {
    if(response.status==200 && response.data.errno==4000){
        go_to_login_page()
    }else{
        return response
    }
}, err => {
    return Promise.reject(err)
})

https://github.com/axios/axios

anjia commented 5 years ago

cookie, localStorage, sessionStorage #43

anjia commented 5 years ago

JSON.stringify

stringify() 字符串,会多个双引号

JSON.stringify('anjia')   // 输出 ""anjia""
anjia commented 5 years ago

ping-pong

服务器心跳:服务器发送ping,浏览器收到了会自动返回pong,且会主动触发服务器的onPong方法

浏览器心跳:浏览器自带了心跳机制。但并不是标准规范,而是厂商们自己设计的