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

最近在搞一个老项目,前端使用的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>
相关推荐
NiceCloud喜云8 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
wordbaby9 小时前
React Native + RNOH:跨页面数据回传的最佳实践与避坑指南
前端·react native
丷丩9 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
Front思10 小时前
AI前端工程师需要具备能力+
前端·人工智能·ai
ZC跨境爬虫12 小时前
跟着 MDN 学CSS day_29:(掌握文本与字体样式的核心艺术)
前端·css·ui·html·tensorflow
李子琪。12 小时前
网络空间安全深度实战:CSRF 漏洞原理剖析与基于 Token 的纵深防御体系构建(全栈实验报告)
前端·安全·csrf
冰暮流星12 小时前
javascript之history对象介绍
前端·笔记
IT_陈寒13 小时前
Vite热更新失灵?你可能漏了这个配置
前端·人工智能·后端
丷丩13 小时前
MapLibre GL JS第19课:实时更新要素
前端·javascript·gis·map·mapbox·maplibre gl js
Mr.Daozhi13 小时前
RAG 进阶实战:跑通 Demo 后我连续翻了 6 次车,逐一修复才真正可用(含 Gradio Web 版)
前端·数据库·langchain·大模型·gradio·rag·科研工具