反向代理解决跨域问题

项目中后端给的数据 图片可能是一个链接网址,这时候就不可避免的需要跨域

直接操作:

1.需要在项目中新增一个app.js

反向代理的配置文件

 2.文件内需要需要引入express cros axios

const express = require('express');
const cors = require('cors');
const axios = require('axios');

const app = express();

// 配置CORS中间件
const corsOptions = {
  origin: 'http://localhost:8080',
  methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
  allowedHeaders: 'Content-Type,Authorization',
};

app.use(cors(corsOptions));

// 定义一个简单的路由
app.get('/api/data', (req, res) => {
  const data = { message: 'This is some data from the server.' };
  res.json(data);
});

// 新增的代理路由,接受图片名称参数
app.get('/api/proxy-image/:imageName', async (req, res) => {
  try {
    const imageNames = {
      image1: 'https://z1.ax1x.com/2023/08/23/pPYdk5t.png',//第一个图片URL
    };

    const imageName = req.params.imageName;

    if (!imageNames[imageName]) {
      res.status(404).send('Image not found.');
      return;
    }

    const imageUrl = imageNames[imageName];
    const response = await axios.get(imageUrl, { responseType: 'arraybuffer' });
    const buffer = Buffer.from(response.data, 'binary');
    
    // 获取图片类型,可以根据实际情况修改 Content-Type
    const imageType = imageUrl.endsWith('.png') ? 'image/png' : 'image/jpeg';

    res.set('Content-Type', imageType);
    res.set('Access-Control-Allow-Origin', '*');
    res.send(buffer);
  } catch (error) {
    res.status(500).send('Failed to retrieve the image.');
  }
});

// 启动Express服务器
const port = process.env.PORT || 9212(设置一个端口号 这个端口号不能被占用!!;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

 3.配置之后启动服务 启动成功后会在终端返回你的端口号

node app.js  //你的文件名字

4.项目中使用

const imageUrl = 'http://localhost:9212/api/proxy-image/image1';

9212是我在app.js(配置文件)中设置的端口号

/api/proxy-image/ 是配置文件中app.get新增的路由

image1就是新增路由中的图片,有1就有2说明可以配置多个图片进行跨域

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Nginx作为反向代理服务器可以用来解决跨域问题。通过将本地的URL前缀映射到需要跨域访问的Web服务器上,Nginx可以将HTTP请求转发到后端的真实服务器上,并通过rewrite命令去掉前缀。这样,真实的服务器可以正确处理请求,而不知道请求来自代理服务器。\[2\] 在Nginx的配置文件中,可以使用location指令来匹配需要跨域访问的路径,并在proxy_pass中填写需要访问的外域API地址。例如,当访问"http://localhost:8088/api/.*"路径时,可以将proxy_pass设置为"http://test.abc.com/",这样实际上访问的是"http://test.abc.com/.*",但在浏览器中显示的仍然是原来的路径"http://localhost:8088/api/.*"。需要注意的是,在匹配路径和代理路径的末尾都不能少斜杠,这是Nginx的规则。修改完nginx.conf文件后,需要重启Nginx才能生效。\[3\] 通过这种方式,Nginx可以实现跨域访问,解决跨域问题。 #### 引用[.reference_title] - *1* [Nginx 反向代理解决跨域问题](https://blog.csdn.net/weixin_43066287/article/details/121104183)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [ajax nginx 转发 sessionid_【Nginx】使用Nginx如何解决跨域问题?看完这篇原来很简单!!...](https://blog.csdn.net/weixin_39954698/article/details/109917716)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [nginx反向代理解决跨域请求问题](https://blog.csdn.net/lm____/article/details/120462636)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值