解决跨域请求:如何将 onload 结果传参到 GenshinVoice API
解决跨域请求的问题可以通过以下两种方式:
- 在服务器端设置响应头信息,允许来自指定来源的跨域请求。在服务器端的API代码中添加以下头部信息:
response.setHeader('Access-Control-Allow-Origin', 'https://ai.3dlingyu.com');
该代码将允许来自'https://ai.3dlingyu.com'域名的请求访问该API。
- 使用代理服务器进行请求。在你的服务器端代码中,通过代理服务器发送请求到目标API,并将响应返回给客户端。这样可以绕过跨域限制,因为客户端实际请求的是你的服务器端,而不是目标API。以下是一个示例的代理服务器代码:
const http = require('http');
const https = require('https');
const url = require('url');
http.createServer(function (req, res) {
// 解析目标URL
const targetUrl = 'https://genshinvoice.top/api' + req.url;
// 发送请求到目标URL
const options = url.parse(targetUrl);
const proxyReq = https.request(options, function (proxyRes) {
// 设置响应头
res.setHeader('Access-Control-Allow-Origin', 'https://ai.3dlingyu.com');
// 将目标API的响应发送给客户端
proxyRes.pipe(res);
});
// 处理请求错误
proxyReq.on('error', function (err) {
console.error('请求目标API发生错误:', err);
res.statusCode = 500;
res.end('请求目标API发生错误');
});
// 将客户端请求发送到目标API
proxyReq.end();
}).listen(3000, function () {
console.log('代理服务器已启动,监听在端口3000');
});
在客户端代码中,将API请求的URL修改为代理服务器的URL,例如:
let url = `http://your-proxy-server:3000/api?speaker=丹恒&text=${content}&format=wav&length=1&noise=0.5&noisew=0.9&sdp_ratio=0.2`;
将'your-proxy-server'替换为你的代理服务器的域名或IP地址。
使用以上两种方法之一,你就可以解决跨域请求的问题,并成功将'onload'事件的结果传参到'https://genshinvoice.top/api'。
原文地址: https://www.cveoy.top/t/topic/nT96 著作权归作者所有。请勿转载和采集!