后端代理
几种常用跨域方式区别:
jsonp : 前端来完成
CORS: 前后端配合完成 (存在预检请求的情况)
后端代理: 后端完成
1. 概念
跨域是浏览器规范,通过同服务器请求数据,不通过浏览器请求,也能解决浏览器限制;
接口转发,转发请求,利⽤http模块实现简单的服务器转发
2. koa-server-http-proxy
利⽤ koa-server-http-proxy中间件实现代理
2.1 官方下载
$ npm install koa-server-http-proxy --save
2.2 引入与使用
官网示例:
const Koa = require('koa')
const app = new Koa()
const proxy = require('koa-server-http-proxy')
app.use(proxy('/api', {
target: 'https://news-at.zhihu.com',
pathRewrite: { '^/api': 'api/4/' },
changeOrigin: true
}))
app.listen(3000)
2.3 两个重要参数:target:" ",pathRewrite:{’’:’’}
koa-server-http-proxy都封装好了,可设置好直接拿来用,自己主要去写target,pathRewrite后的两个参数
在服务器配置好两个参数
target:" "
里是要跨域的地址
pathRewrite:{ ' ^/api ' : ' '}
(1)接口要与前端对应!!!
(2) ^ : 以什么开头,该例子指把前端以/api开头的替换成空字符
3. 代码示例
服务器端代码:
const koaServerHttpProxy = require("koa-server-http-proxy");
//服务器端代理 :接口转发 (服务器端代理为正向代理,客户端代理为反向代理)
app.use(koaServerHttpProxy("/api",{
target:"http://localhost:4000",
// pathRewrite:{'^/api':'/api/4/'}, // 这个对应路由为/api/4/Serverpost
pathRewrite:{'^/api':''},// 接口要与前端对应!!!
// ^:以什么开头 这里指把前端以/api开头的替换成空字符 在4000端口号那里设置一个路由
// 这个对应路由为/Serverpost
changeOrigin: true
}));
// ...
app.listen(5000);
前端浏览器代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>5000端口</h1>
<button class="btn1">请求非跨域/同源</button>
<button class="btn2">请求跨域/非同源</button>
<script>
document.querySelector(".btn1").onclick = function(){
let xhr = new XMLHttpRequest();
xhr.open("post","/Serverpost",true); //自家访问
xhr.onload = function(){
console.log(xhr.responseText);
}
xhr.send();
}
//非同源情况
document.querySelector(".btn2").onclick = function(){
let xhr = new XMLHttpRequest();
xhr.open("post","/api/Serverpost",true); //访问他家 "跨域暗号/具体端口"
xhr.onload = function(){
console.log(xhr.responseText);
}
xhr.send();
}
</script>
</body>
</html>
跨域到4000端口号的服务器 中的 路由配置:
router.post("/Serverpost",ctx=>{
ctx.body = "小点声,我是偷摸来的~"
})
app.use(router.routes());
app.listen(4000);