不用框架,本地启动接口代理

跨域的问题已经是老生常谈了,解决的办法很多,现在几乎都用 webpack、vite 等工具,配置个代理,解决起来不要太容易。

当在一些很古早的项目,或者非常临时的,想要在项目里请求一下服务器的接口,这时候,很少有那么好的后端临时开启所有可跨域,需要前端自己解决。估计大部分都是直接跟后端说跨域,就是要接口层面解决,前端其实也是能做,只是很少有人去了解。

使用框架,无非就是本地启动了一个服务,转发了本地发起的请求,在没有使用框架的情况下,我们也可以使用 node,自己启动一个服务做代理。这边有一个前提:
静态访问是用本地服务,就是 localhost 访问(vscode 使用 live server 插件,或者全局安装 npm 包 anywhere/http-server)

先使用 Ajax 进行一个请求:

  $.ajax({
    url: "http://localhost:3000//bam/inbound/receipt/search-by-paging",
    headers: {
      'Authorization': "Basic aXRlbXNob3BAaXRlbS5jb206UGFzczEyMzQ1Ng==",
      "company-id": "Dff1",
      "x-channel": "WEB",
    },
    method: "POST",
    success: function (response) {
      console.log("items", response);
    },
  });

我们需要使用 http-proxy 这个包,所以要自己新建一个文件夹:

//在新建文件夹里面执行,-y是默认配置
npm init -y

npm i http-proxy

//新建一个文件proxy.js,文件名随便取
const http = require("http");
const httpProxy = require("http-proxy");

const proxy = httpProxy.createProxyServer({});

const server = http.createServer((req, res) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Content-Type, Authorization, x-channel, company-id, authority"
  ); // 添加 x-channel 到允许的请求头列表

  if (req.method === "OPTIONS") {
    res.writeHead(200);
    res.end();
  } else {
    proxy.web(req, res, {
      target: "https://scm-stage.item.com",
      changeOrigin: true,
    });
  }
});

proxy.on("error", (error, req, res) => {
  console.error("Proxy Error:", error);
  res.writeHead(500, {
    "Content-Type": "text/plain",
  });
  res.end("Proxy Error");
});

server.listen(3000, () => {
  console.log("Proxy server listening on port 3000");
});

最后就是执行这个文件了,用 code runner 也好还是 node proxy.js 也好,启动了就行,接着就会直接进行代理转发了。

错误一,是代理那边请求允许的头部要加进去:

Access to XMLHttpRequest at 'http://localhost:3000//bam/inbound/receipt/search-by-paging' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: Request header field company-id is not allowed by Access-Control-Allow-Headers in preflight response.

错误二,请求进行了 options 预请求,所以要单独配置 options 的情况:

Access to XMLHttpRequest at 'http://localhost:3000//bam/inbound/receipt/search-by-paging' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

一些不用框架,或者临时使用的话,还是蛮好用的,当作一个项目放着,用的时候就启动,甚至可以放到自己所在的项目里面,当作工具用。

欢迎关注订阅号 coding个人笔记

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值