跨域请求 & ajax 自定义header

今天看到某跨域请求,会把appId, appKey这种每次都需要传的字段放在Header中。

这样我们只用关注真正需要的发送的数据。
每次都必须传的appId, appKey 只用配置一次就能永久使用。

以Jquery ajax 为例

       $.ajaxSetup({
            headers: {
                "RIDER-APPID": APPID,
                "RIDER-APPKEY": APPKEY
            }
        });

之后浏览器会先发送一个 OPTIONS 请求

Request URL:http://127.0.0.1:3000/api/document
Request Method:OPTIONS
Status Code:200 OK
Remote Address:127.0.0.1:3000

首先知识点学习
浏览器将CORS请求分成两类:简单请求(simple request)和非简单请求(not-so-simple request)。
只要同时满足以下两大条件,就属于简单请求。

(1) 请求方法是以下三种方法之一:
HEAD
GET
POST
(2)HTTP的头信息不超出以下几种字段:
Accept
Accept-Language
Content-Language
Last-Event-ID
Content-Type:只限于三个值application/x-www-form-urlencoded、multipart/form-data、text/plain

简单请求浏览器会在 header 加上 Origin:http://zhangyili.com 字段
服务器如果返回 Access-Control-Allow-Origin 对应的域名 或者 * 则可以浏览器同意访问。
否则浏览器会拦截。


csrf请求默认不发送cookie
若要发送需要
ajax设置 xhr.withCredentials = true;
浏览器返回 Access-Control-Allow-Credentials: true


Access-Control-Expose-Headers 关系到设置自定义heaer

**

OPTIONS 是什么

This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.

这个请求用来试探服务器该接口是否有权限,避免了直接访问报错。常用于跨域
我们来看看服务器返回了什么就知道作用了

Access-Control-Allow-Headers:RIDER-APPID, RIDER-APPKEY
Access-Control-Allow-Methods:POST, GET, OPTIONS, DELETE, PUT
Access-Control-Allow-Origin:*
Access-Control-Max-Age:1000

服务器允许了 我们的header
之后浏览器会在发起真正的请求 拿到数据

Request URL:http://127.0.0.1:3000/api/document
Request Method:POST
Status Code:200 OK
Remote Address:127.0.0.1:3000

Pragma:no-cache
Referer:http://127.0.0.1:8081/demo/test.html
RIDER-APPID:2960644235866
RIDER-APPKEY:6f2c8ccaf19e6a3957c8a9df0a0b588f27795886
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36

最后show一下服务端Node代码 框架是koa

router.options('/document', function *(next){
    let res = this.response;
    this.set('Access-Control-Allow-Origin', '*');
    this.set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
    this.set('Access-Control-Max-Age', 1000);
    this.set('Access-Control-Allow-Headers', 'RIDER-APPID, RIDER-APPKEY');
});
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,841评论 18 139
  • XMLHttpRequest的跨域请求 动态添加一个标签,而script标签的src属性是没有跨域的限制的。这样说...
    葛高召阅读 22,542评论 0 0
  • 1. 所谓跨域 跨域是一种浏览器同源安全策略,也即浏览器单方面限制脚本的跨域访问。很多人可能误认为资源跨域时无法请...
    blurooo阅读 6,180评论 11 54
  • 受浏览器的同源策略限制,JavaSript只能请求本域内的资源。跨域资源共享(Cross-Origin Resou...
    AISpider阅读 260评论 0 0
  • CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。 ...
    奇特思维家阅读 1,136评论 0 3