React网站集成vCenter API遇CORS及证书验证问题求解决方案
解决vCenter API与React集成的CORS及证书验证问题
我有一台vCenter,想要和React网站集成,用Axios实现API调用功能。以下是编写的Axios GET请求代码:
const src = "https://x.x.x.x/rest/vcenter/vm" axios .get(src, { method: 'get', auth: { username: "*", password: "*" }, headers: {'vmware-api-session-id': '1b54796fd291d3fe3bf516f26bd54236', 'Content-Type': 'application/json','Access-Control-Allow-Origin': '*','Accept': 'application/json', 'Access-Control-Allow-Methods': 'DELETE, POST, GET, OPTIONS', 'Access-Control-Allow-Headers': 'Origin, X-Auth-Token, Content-Type, Authorization, X-Requested-With'}, responseType: 'json', httpsAgent: { rejectUnauthorized: false } }) .then(function (response) { console.log("success!!"); console.log(response) }) .catch(function (response) { //handle error console.log("error!!"); console.log(response) });
请求触发CORS错误:
Access to XMLHttpRequest at 'https://x.x.x.x/rest/vcenter/vm' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
尝试自建代理解决时,返回以下错误:
code: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'
本地可通过CURL正常请求该API,以下是可行解决方案:
一、先修正Axios请求的错误配置
- 移除请求头中的
Access-Control-Allow-Origin、Access-Control-Allow-Methods、Access-Control-Allow-Headers:这些是服务器返回给浏览器的响应头,前端请求时不需要添加,会干扰预请求逻辑。 - 删除冗余的
method: 'get':Axios的get方法默认就是GET请求,无需重复配置。 - 正确配置
httpsAgent:需要使用https.Agent实例,而非普通对象,先引入https模块:const https = require('https'); // 修正后的Axios配置片段 axios.get(src, { auth: { username: '你的用户名', password: '你的密码' }, headers: { 'vmware-api-session-id': '1b54796fd291d3fe3bf516f26bd54236', 'Content-Type': 'application/json', 'Accept': 'application/json' }, responseType: 'json', httpsAgent: new https.Agent({ rejectUnauthorized: false }) })
二、解决CORS及代理证书问题的核心方案
1. 正确配置React本地代理
如果使用Create React App,通过代理转发请求避开浏览器CORS限制,同时处理证书验证:
- 在项目根目录新建
setupProxy.js文件,添加以下代码:const { createProxyMiddleware } = require('http-proxy-middleware'); const https = require('https'); module.exports = function(app) { app.use( '/rest', createProxyMiddleware({ target: 'https://x.x.x.x', changeOrigin: true, secure: false, // 禁用证书验证 agent: new https.Agent({ rejectUnauthorized: false }) }) ); }; - 修改Axios请求地址为
/rest/vcenter/vm,请求会自动通过本地代理转发到vCenter。
2. 在vCenter上直接配置CORS规则
若拥有vCenter管理权限,可直接添加允许React域名的CORS规则,从根源解决跨域:
- 登录vCenter管理界面,进入系统配置 > 高级设置
- 添加以下键值对:
config.vpxd.rest.cors.allowOrigin=http://localhost:3000config.vpxd.rest.cors.allowMethods=GET,POST,PUT,DELETE,OPTIONSconfig.vpxd.rest.cors.allowHeaders=Content-Type,Authorization,vmware-api-session-id
- 重启vCenter服务生效,之后前端可直接请求vCenter API,无需代理。
3. 通过后端中转请求
利用后端服务无CORS限制的特性,搭建简单中转服务:
- 示例Node.js(Express)后端代码:
const express = require('express'); const axios = require('axios'); const https = require('https'); const app = express(); const port = 5000; app.get('/api/vms', async (req, res) => { try { const response = await axios.get('https://x.x.x.x/rest/vcenter/vm', { auth: { username: '你的用户名', password: '你的密码' }, headers: { 'vmware-api-session-id': '你的sessionId' }, httpsAgent: new https.Agent({ rejectUnauthorized: false }) }); res.send(response.data); } catch (err) { res.status(err.response?.status || 500).send(err.response?.data || '请求失败'); } }); app.listen(port, () => console.log(`中转服务运行在 http://localhost:${port}`)); - 前端Axios请求地址改为
http://localhost:5000/api/vms即可。
注:本地CURL能正常请求是因为CURL不受浏览器CORS策略限制,跳过证书验证的CURL命令为:
curl -k https://x.x.x.x/rest/vcenter/vm -u 用户名:密码
内容的提问来源于stack exchange,提问作者Alexander Sinchenko
相关产品推荐
相关产品推荐

