前后端分离项目前端页面开发远程调试代理解决跨域问题方法

最近在搞一个老项目,前端使用的vue构建的,然后把静态资源配置在nginx项目中,不大方便使用node环境配置代理来映射到远程的后端服务数据接口上,所以搜集了点资料通过nginx的反向代理来映射到对应的服务器数据接口上,解决了跨域之类的问题,主要是nginx配置代理那块,还可以增加cookie和agent。上代码:

服务端数据接口

https://domain/api/api-u/users/current

nginx配置文件

复制代码
location / {
	root   html;
	index  index.html index.htm;
}

location /api/ {
	proxy_pass https://domain/api/;
	proxy_set_header Cookie "SESSION=XXX";
	proxy_set_header Host domain;
	proxy_set_header Referer https://domain;
	proxy_set_header Origin https://domain;
	proxy_set_header User-Agent $http_user_agent;
	proxy_ssl_server_name on;
	proxy_ssl_verify off;
	
	proxy_connect_timeout 30s;
	proxy_send_timeout 30s;
	proxy_read_timeout 30s;

	if ($request_method = OPTIONS) {
		add_header Access-Control-Allow-Origin $http_origin;
		add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
		add_header Access-Control-Allow-Headers "Content-Type, Authorization";
		add_header Access-Control-Max-Age 1728000;
		add_header Content-Length 0;
		add_header Content-Type text/plain;
		return 204;
	}
}

前端代码(AIGC)

html 复制代码
<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>自动请求远程接口</title>
</head>
<body>
  <h1>自动请求测试</h1>
  <p>页面加载中... 正在请求远程接口 <code>/api/api-b/announcement/show</code></p>
  <div id="result">加载中...</div>

  <script>
    // 页面加载完成后自动发起请求
    window.addEventListener('DOMContentLoaded', async () => {
      const resultDiv = document.getElementById('result');

      try {
        const response = await fetch('/api/api-u/users/current', {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json'
          }
        });

        if (!response.ok) {
          throw new Error(`服务器返回错误: ${response.status} ${response.statusText}`);
        }

        const data = await response.json();
        resultDiv.innerHTML = `
          <h2>✅ 请求成功</h2>
          <pre>${JSON.stringify(data, null, 2)}</pre>
        `;
      } catch (error) {
        resultDiv.innerHTML = `
          <h2 style="color:red;">❌ 请求失败</h2>
          <p><strong>错误信息:</strong> ${error.message}</p>
          <p>请检查:</p>
          <ul>
            <li>Nginx 是否已启动</li>
            <li>nginx.conf 中路径是否正确</li>
            <li>远程接口是否可访问</li>
          </ul>
        `;
        console.error('自动请求失败:', error);
      }
    });
  </script>
</body>
</html>
相关推荐
Nan_Shu_61417 分钟前
学习: Threejs (2)
前端·javascript·学习
G_G#25 分钟前
纯前端js插件实现同一浏览器控制只允许打开一个标签,处理session变更问题
前端·javascript·浏览器标签页通信·只允许一个标签页
@大迁世界41 分钟前
TypeScript 的本质并非类型,而是信任
开发语言·前端·javascript·typescript·ecmascript
GIS之路1 小时前
GDAL 实现矢量裁剪
前端·python·信息可视化
是一个Bug1 小时前
后端开发者视角的前端开发面试题清单(50道)
前端
Amumu121381 小时前
React面向组件编程
开发语言·前端·javascript
持续升级打怪中1 小时前
Vue3 中虚拟滚动与分页加载的实现原理与实践
前端·性能优化
GIS之路1 小时前
GDAL 实现矢量合并
前端
hxjhnct1 小时前
React useContext的缺陷
前端·react.js·前端框架
前端 贾公子2 小时前
从入门到实践:前端 Monorepo 工程化实战(4)
前端