最近在搞一个老项目,前端使用的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>