1.node代理服务器解决跨域
原理
- 跨域是因为浏览器的同源安全策略所导致的,但是服务器与服务器、app与服务器、小程序与服务器是不存在跨域的
- 所以利用nodejs搭建一个代理服务器,将本地开发的前端代码托管到这个代理服务器的静态资源中
- 将静态资源的请求地址换成代理服务器地址
- 在这个代理服务器中使用
http-proxy-middleware
三方中间件来转发请求和响应
- 当客户端发起请求,实际上是请求这个代理服务器(因为前端资源和代理服务器是在一起的符合同源策略),然后代理服务器拿到请求后,向目标服务器发起请求,目标服务器接送到请求然后响应数据给代理服务器,代理服务器再将结果给到客户端
- 其实webpack中的代理服务器也是用到这个中间件的,总所周知,webpack是基于node的,我们可以想一下,用webpack来启动文件也是需要启动服务的,然后访问静态资源,原理和我们现在编写代码一样
安装
npm i http-proxy-middleware
7.4.1.使用
客户端
<script>
// 将请求的地址是代理服务器
const requst = new Request('http://localhost:8001/api/test', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
})
fetch(requst).then((res) => {
console.log(res)
})
</script>
代理服务器
-
target
:要代理到的服务器,可以是域名也可以是ip+端口号; -
changeOrigin
:虚拟托管网站,如果为true
,源服务器获取的req.header的信息就是他自己的header,如果为false
那么获取的header信息就是代理服务器的-
有的服务器为了做反扒,会判断req.header.host的 如果你的请求不是当前服务器地址的host是不给你数据的
-
比如服务器地址是http://123.124.123.112:8000 但是用代理我们的请求地址是http://127.0.0.1:3000,那么服务器在获取req.header.host的时候。如果
changeOrigin:true
那么请求的host就是http://123.124.123.112:8000 反之则是http://127.0.0.1:3000
-
-
ws
:是否代理websockets
; -
secure
:是否代理https请求; -
pathRewrite
:重写路径,将":"前的路径替换为后面的路径;
const express = require('express')
const httpProxyMiddleware = require('http-proxy-middleware')
const app = express()
const options = {
target: 'http://localhost:8002',
changeOrigin: true,
ws: true,
secure: true,
pathRewrite: {
'^/api': '',
},
}
// 托管静态资源
app.use(express.static('../client'))
app.use(
'/api',
httpProxyMiddleware.createProxyMiddleware(options),
(req, res, next) => {
next()
}
)
// 监听端口
app.listen(8001, () => {
console.log('8001端口监听成功')
})