背景说明
前后端分离项目要解决的第一个问题前端本地开发如何解决ajax的跨域问题,一般情况下都是使用Nginx配置反向代理进行解决,另外还有一种方案是通过nodejs进行接口代理,现在前端的开发都是基于nodejs进行开发,保持了技术栈的统一。
官网文档
https://www.npmjs.com/package/http-proxy-middleware
https://github.com/chimurai/http-proxy-middleware
解决方案
服务源码
DeptController
@RestController
@RequestMapping("/dept")
public class DeptController {
@GetMapping("/test")
public String test(){
return "/dept/test";
}
}
UserController
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping("/test")
public String test(){
return "/user/test";
}
}
代理代码
创建工程svc-proxy
PS D:\study\proxy> npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help init` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (proxy) svc-proxy
version: (1.0.0)
description: rest api proxy
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to D:\study\proxy\package.json:
{
"name": "svc-proxy",
"version": "1.0.0",
"description": "rest api proxy",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this OK? (yes)
PS D:\study\proxy>
安装模块
PS D:\study\proxy> npm i http-proxy-middleware -D
PS D:\study\proxy> npm i express -D
编写源码文件index.js
var express = require("express");
var {createProxyMiddleware}= require('http-proxy-middleware');
var app = express();
app.use(
createProxyMiddleware('/dept',{
"target": 'http://localhost:8080'
})
);
app.use(
createProxyMiddleware('/user/**',{
"target": 'http://localhost:8080'
})
);
app.listen(3000);
运行项目
PS D:\study\proxy> node index.js
[HPM] Proxy created: /dept -> http://localhost:8080
[HPM] Proxy created: /user/** -> http://localhost:8081
访问链接结果如下所示:
Get http://localhost:3000/dept/test
/dept/test
Get http://localhost:3000/user/test
/user/test
由上可以看出代理可以正常使用
参考文档
https://www.cnblogs.com/zhaoweikai/p/9969282.html
https://juejin.cn/post/6844903829939437581
高级方案
如果项目使用webpack作为构建工具的话,可以引入webpack-dev-server进行配置跨域方案,webpack-dev-server是一个小型的nodejs服务器,是基于express框架的,用于实时监听和打包编译静态资源,其中有一个属性是proxy,是专门用来配置代理请求接口的,webpack-dev-server的代理方案是引用了http-proxy-middleware模块进行设置的。
网友评论