新手求助:Cyclic.sh上网页标题获取API报错排查
问题排查与修复方案
你的API出现错误主要是几个核心问题导致的,下面逐一说明并给出修复代码:
1. 异步函数未正确处理
getTitle是异步函数,调用后返回的是Promise对象,直接把Promise传给res.write()会导致输出Promise的字符串形式而非实际标题;同时未等待异步操作完成就调用res.end(),会提前结束响应。
2. Node.js环境不支持浏览器的Request构造函数
Node.js中没有浏览器端的Request对象,直接使用会抛出错误,应直接通过fetch的参数传递请求配置。
3. URL处理缺失解码步骤
浏览器会对请求URL中的特殊字符编码,直接截取后的URL处于编码状态,需解码后再传入fetch,否则会导致请求地址错误。
4. 正则表达式匹配逻辑冗余且错误
原正则使用HTML实体<,但实际获取的HTML是原始文本,应直接匹配<;同时可简化正则,直接提取标题文本内容,无需多次截取替换。
5. 请求头配置不合理
Node.js环境下无需设置mode: 'cors',且部分网站会校验User-Agent,添加合理的UA可避免被拒绝请求。
修复后的完整代码
const http = require('http'); // Helper function to get the title of a web page async function getTitle(url) { try { // 解码URL,处理浏览器编码的情况 const decodedUrl = decodeURIComponent(url); const response = await fetch(decodedUrl, { method: 'GET', headers: { 'Content-Type': 'text/html', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36' } }); // 检查响应状态,非200直接返回空 if (!response.ok) { console.error(`Request failed with status: ${response.status}`); return ''; } const html = await response.text(); // 简化正则,直接匹配标题内容 const titleMatch = html.match(/<title.*?>(.*?)<\/title>/i); return titleMatch ? titleMatch[1].trim() : ''; } catch (err) { console.error(`Failed to retrieve title with error: ${err}`); return ''; } } http.createServer(async function (req, res) { // 处理根路径请求 if (req.url === '/') { res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('Please provide a URL after the API address, e.g., /https://example.com'); res.end(); return; } // 截取并处理目标URL const targetUrl = req.url.slice(1); console.log(`Requesting title for: ${targetUrl}`); // 等待异步函数返回结果 const title = await getTitle(targetUrl); // 设置响应头,处理跨域 res.writeHead(200, { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': '*' }); res.write(title || 'Failed to retrieve title'); res.end(); }).listen(process.env.PORT || 3000);
额外优化点
- 添加根路径提示,避免用户直接访问API根地址无反馈
- 增加响应状态码检查,处理请求失败的情况
- 添加跨域响应头,方便前端调用
- 给标题文本做trim处理,去除多余空格
内容的提问来源于stack exchange,提问作者Olivier
相关产品推荐
相关产品推荐

