一、JSONP
JSONP 是一种借助script元素实现跨域的技术,它不会使用XHR对象。
script 元素有以下两个特点
1.它的src属性能够访问任何URL资源,不会受同源策略的限制。
2.如果访问的资源包含js代码,那么在下载完成后会自动执行。
JSONP就是基于这两点,再与服务器配合来实现跨域请求的
优点:
-
缺点:
它支持 GET 请求而不支持 POST 等其它类行的 HTTP 请求。
- 无法捕获 Jsonp 请求时的连接异常,只能通过超时进行处理
二、CORS
跨域资源共享(CORS) 是一种机制,它使用额外的 HTTP 头来告诉浏览器 让运行在一个 origin (domain) 上的 Web 应用被准许访问来自不同源服务器上的指定的资源。2.1 在 node 中的解决方式
app.use(async (ctx, next) => {ctx.set("Access-Control-Allow-Origin", ctx.headers.origin);ctx.set("Access-Control-Allow-Credentials", true);ctx.set("Access-Control-Request-Method", "PUT,POST,GET,DELETE,OPTIONS");ctx.set("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, cc");if (ctx.method === "OPTIONS") {ctx.status = 204;return;}await next();});// 直接使用中间件const cors = require("koa-cors");app.use(cors());
2.2 关于cors cookie 问题
想要传递 cookie 需要满足 3 个条件
1.web 请求设置withCredentials
2.Access-Control-Allow-Credentials 为 true// 原生 xml 的设置方式var xhr = new XMLHttpRequest();xhr.withCredentials = true;// axios 设置方式axios.defaults.withCredentials = true;
3.Access-Control-Allow-Origin为非 *三、代理
3.1 正向代理

正向代理即是客户端代理, 代理客户端, 服务端不知道实际发起请求的客户端。3.2 反向代理

反向代理即是服务端代理, 代理服务端, 客户端不知道实际提供服务的服务端。
nginx 配置反向代理server {listen 80;server_name local.test;location /api {proxy_pass http://localhost:8080;}location / {proxy_pass http://localhost:8000;}}
四、websorket
这种方式本质没有使用了 HTTP 的响应头, 因此也没有跨域的限制
back-end<script>let socket = new WebSocket("ws://localhost:8080");socket.onopen = function() {socket.send("test");};socket.onmessage = function(e) {console.log(e.data);};</script>
const WebSocket = require("ws");const server = new WebSocket.Server({ port: 8080 });server.on("connection", function(socket) {socket.on("message", function(data) {socket.send(data);});});
