CORS(Cross-origin resource sharing),跨域资源共享,是一份浏览器技术的规范,用来避开浏览器的同源策略
简单来说就是解决跨域问题的除了jsonp外的另一种方法;比jsonp更加优雅。
options是浏览器默认行为,表示的是非简单请求,会请求两次
写在app use里可以成为公用,不用每个router都添加cors
1.(‘Access-Control-Allow-Origin’, ‘*’) Origin源头,这个表示任意域名都可以访问,默认不能携带cookie了。(必须字段)
*通配符,表示所有网址都可以跨域请求,一般不这样写,写个指定网址
res.header('Access-Control-Allow-Origin', 'http://www.baidu.com');// 这样写,只有www.baidu.com 可以访问。2.Access-Control-Allow-Credentials:布尔值 Credentials资格,true允许携带cookie;(可选字段)
客户端设置允许携带用户凭证(写在客户端html)
xhr.withCredentials = true;服务端设置允许携带cookie(写在服务器js)
ctx.set("Access-Control-Allow-Credentials",true);3.Access-Control-Allow-Headers 允许设置的头部信息
("Access-Control-Allow-Headers","Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild")4.Access-Control-Allow-Methods设置允许请求的Methods方法
res.header('Access-Control-Allow-Origin', '*'); // 这个表示任意域名都可以访问,这样写不能携带cookie了。res.header('Access-Control-Allow-Origin', 'http://www.baidu.com');// 这样写,只有www.baidu.com 可以访问。res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');//设置方法,允许的方法,没有写就不允许5.Access-Control-Expose-Headers 允许客户端获取的Headers头部key
CORS请求时,XMLHttpRequest对象的getResponseHeader()方法只能拿到6个基本字段:Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma。如果想拿到其他字段,就必须在Access-Control-Expose-Headers里面指定。
预检请求(非简单请求,请求两次)
下面是简单的请求直接发送GET
HEAD
POST
content-type
text/plain
multipart/form-data
application/x-www-form-urlencoded
下面是预检请求PUT
DELETE
CONNECT
OPTIONS
TRACE
PATCH
axios后端代理跨域是浏览器规范,通过同服务器请求数据,不通过浏览器请求,也能解决浏览器限制;
npm i axios -saxios流程:
3000html先请求自己getData接口—>3000js通过axios转发到4000js—>4000js结果返还到3000js.res—>3000js.res返还到3000html
利用 koa-server-http-proxy中间件实现代理 npm i koa-server-http-proxy -s引入 const koaServerHttpProxy = require(“koa-server-http-proxy”);
用法
app.use(koaServerHttpProxy('/api', { target: 'http://localhost:4000', pathRewrite: { '^/api': '' }}))会先把api地址写一个空