一、代理分正向代理、反向代理

正向代理

一、图例:
代理前
image.png
代理后:这样所有的资源以及请求都在一个域名下了
image.png

node代理

http-proxy-middleware

一、以下工具都是通过http-proxy-middleware实现代理

| 【示例】webpack 4.x```javascript const path = require(“path”); const HtmlWebpackPlugin = require(“html-webpack-plugin”);

module.exports = { entry: { index: “./index.js” }, output: { filename: “bundle.js”, path: path.resolve(__dirname, “dist”) }, devServer: { port: 8000, proxy: { “/api”: { target: “http://localhost:8080“ } } }, plugins: [ new HtmlWebpackPlugin({ filename: “index.html”, template: “webpack.html” }) ] };

  1. ```javascript
  2. <button id="getlist">获取列表</button>
  3. <button id="login">登录</button>
  4. <script src="https://cdn.bootcss.com/axios/0.19.2/axios.min.js"></script>
  5. <script>
  6. axios.defaults.withCredentials = true;
  7. getlist.onclick = () => {
  8. axios.get("/api/corslist").then(res => { // 前端接口请求方式,改为不带域名(因为现在是同域请求了)
  9. console.log(res.data);
  10. });
  11. };
  12. login.onclick = () => {
  13. axios.post("/api/login");
  14. };
  15. </script>

| | —- |

| 【示例】vue-cli 2.x```javascript proxyTable: { ‘/api’: { target: ‘http://localhost:8080‘, } },

  1. |
  2. | --- |
  3. | 【示例】vue-cli 3.x```javascript
  4. module.exports = {
  5. devServer: {
  6. port: 8000,
  7. proxy: {
  8. "/api": {
  9. target: "http://localhost:8080"
  10. }
  11. }
  12. }
  13. };

| | —- |

| 【示例】Parcel(2.x)```javascript { “/api”: { “target”: “http://localhost:8080“ } }

 |
| --- |

<a name="Db4zN"></a>
### cors-anywhere
一、缺点

- 无法专递 cookie,原因是因为这个是一个代理库,作者觉得中间传递 cookie 太不安全了。详情[issue](https://github.com/Rob--W/cors-anywhere/issues/208#issuecomment-575254153)
| 【示例】```javascript
// Listen on a specific host via the HOST environment variable
var host = process.env.HOST || "0.0.0.0";
// Listen on a specific port via the PORT environment variable
var port = process.env.PORT || 7777;

var cors_proxy = require("cors-anywhere");
cors_proxy
  .createServer({
    originWhitelist: [], // Allow all origins
    requireHeader: ["origin", "x-requested-with"],
    removeHeaders: ["cookie", "cookie2"]
  })
  .listen(port, host, function() {
    console.log("Running CORS Anywhere on " + host + ":" + port);
  });
<script src="https://cdn.bootcss.com/axios/0.19.2/axios.min.js"></script>
<script>
  axios.defaults.withCredentials = true;
  getlist.onclick = () => {
    axios
      .get("http://127.0.0.1:7777/http://127.0.0.1:8080/api/corslist")
      .then(res => {
        console.log(res.data);
      });
  };
  login.onclick = () => {
    axios.post("http://127.0.0.1:7777/http://127.0.0.1:8080/api/login");
  };
</script>

| | —- |

charles

一、tools-map remote中设置

image.png

反向代理

http服务器

nginx

一、当前域能获取到静态资源和接口。
image.png

| 【示例】配置nginx```javascript 127.0.0.1 local.test

```javascript
server {
  listen 80;
  server_name local.test;
  location / {
    proxy_pass http://localhost:8000;
  }
  location /api {
    proxy_pass http://localhost:8080;
  }
}

| | —- |