通过node中间件http-proxy-middleware做正向代理

  • 它可以利用node没有浏览器安全级别的跨域限制解决跨域问题

  • 安装 http-proxy-middleware 模块

npm i http-proxy-middleware -S
const http = require('http');
const { createProxyMiddleware } = require('http-proxy-middleware');

const server = http.createServer((req, res) => {
  const urlStr = req.url;
  if (/^\/api\/v3\/search/.test(urlStr)) {
    const proxy = createProxyMiddleware({
      target: 'https://so.csdn.net',
      changeOrigin: true
    });
    proxy(req, res);
  } else {
    console.log('error');
    res.write('error');
  }
  // res.end();
});

server.listen(3000, () => {
  console.log('http://localhost:3000');
});