我这里有一个棘手的问题。我创建了一个API,该API将从外部API中获取一些数据。例如:
我在当前的api上具有此端点:
/api/items?q=
在负责此操作的路线上,我有以下代码:
itemsRouter.get("/", async (req, res) => {
const { q } = req.query;
try {
const url = new URL(`externalapiurl?q=${q}`);
console.log(url);
});
} catch (error) {
logger.error(error);
}
});
但是,如果我用console.log
检查我的网址,则该网址始终以espaço编码打印,例如:/search?q=%E2%80%8Biphone'
如果我从节点终端上的new URL
中检查url对象,则在我的q键上可以看到一些空格:
{ 'q' => ' iphone' }
URL对象打印如下:
href:
'externalapiurl?q=%E2%80%8Bapple%20iphone',
origin: 'externalapiurl',
protocol: 'https:',
username: '',
password: '',
host: 'externalapiurl',
hostname: 'externalapiurl',
port: '',
pathname: 'externalapiurl',
search: '?q=%E2%80%8Bapple%20iphone',
searchParams: URLSearchParams { 'q' => ' iphone' },
hash: '' }
因此,请求没有正确提出。我已经尝试过encodeURI和encodeURIComponent,但是问题仍然存在。
PS:此新网址来自const URL = require("url").URL;
而且我正在使用node-fetch
处理网址调用。
任何帮助将不胜感激!谢谢。