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

最近在搞一个老项目,前端使用的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>
相关推荐
云水一下1 天前
从零开始!VMware安装Fedora Workstation 44桌面系统完整教程
前端
小码哥_常1 天前
安卓黑科技:实现多平台商品详情页一键跳转APP
前端
killerbasd1 天前
还是迷茫 5.3
前端·react.js·前端框架
不会敲代码11 天前
TCP/IP 与前端性能:从数据包到首次渲染的底层逻辑
前端·tcp/ip
kyriewen1 天前
奥特曼借GPT-5.5干杯,而你的Copilot正按Token收钱
前端·github·openai
AC赳赳老秦1 天前
投标合规提效:用 OpenClaw 实现标书 / 合同自动审核、关键词校验、格式优化,降低废标风险
开发语言·前端·python·eclipse·emacs·deepseek·openclaw
kyriewen1 天前
代码写成一锅粥?3个设计模式让你的项目“起死回生”
前端·javascript·设计模式
千寻girling1 天前
《 Git 详细教程 》
前端·后端·面试
之歆1 天前
DAY08_CSS浮动与行内块布局实战指南(下)
前端·css
yqcoder1 天前
CSS Position 全解析:5 种定位模式详解
前端·css