一步一步实现本地 node 代理转发请求实现跨域访问 API

前端跨域

vue-cli 跨域

一般设置 vue.config.js 里的 devServer.proxy , 本质是构建一个开发环境下的本地 node 服务器,进行请求转发

生产跨域

前后端未分离时,一般不会有跨域问题;在分离布署下,前端服务器一般是使用 Nginx 转发请求,少数是在 api 服务器上设置 Access-Control-Allow-Origin

花式跨域

  • postMessage (推荐)
  • jsonp
  • 其它

一步一步实现本地 node 代理转发请求

1. node 下载与安装

Node.js 安装配置

2. 安装 Express 框架 方便构建 web 服务

1
npm install express --save

3. 安装 express-http-proxy 代理插件

1
npm install express-http-proxy --save

4. 入口文件 index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
var express = require('express');

var app = express();
app.use(express.json());

// 转发到 http://api.xxx.com
const httpProxy = require('express-http-proxy');
const userServiceProxy = httpProxy('http://api.xxx.com', {
// 请求路径解析,去掉标识串 /api
proxyReqPathResolver: function (req) {
return req.url.replace('/api', '');
},
});

// 设置 /api 开头的链接执行代理
app.get('/api/*', (req, res, next) => {
userServiceProxy(req, res, next);
});

// 把 /public 当作根目录,/public内的文件都为静态资源
app.use('/', express.static('public'));

app.get('*', function (req, res) {
res.send('404');
});

var server = app.listen(8081, function () {
var host = server.address().address;
var port = server.address().port;
console.log('应用实例,访问地址为 http://%s:%s', host, port);
});

5. 测试 HTML 文件 index.html (位于/public)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 以/api开头,将被转发
// 实际请求地址为: http://api.xxx.com/getUserInfo
fetch('/api/getUserInfo', {
method: 'GET',
headers: new Headers({
'Content-Type': 'application/json',
}),
})
.then(res => res.text())
.catch(error => {
console.error('- Error:', error);
})
.then(response => {
console.log('- Success:', response);
document.write(response);
});

编辑文章✏