一直在做react然后遇到类似的问题
Uncaught URIError: This is likely caused by an invalid percent-encoding
我目前正在使用新闻 API,其中一些文章可能包括
%
。我的整个应用程序依赖于在 url 中显示新闻文章名称,因为我使用 this.props.match.params.id
我试图在网上搜索解决方案,但在解决这个确切问题时,大多数人都不清楚。
这个问题有简单的解决方法吗?
您需要将
encodeURIComponent()
与您收到的路径一起用作参数:
例子:
const receivedArticleName = encodeURIComponent('Article Name with %');
由于您使用的是 API,一旦收到它,将您的 URL 变量设置为 receivedArticleName 即可。
这对我有用。
function navigate(data: Partial<Saturation>) {
if (data.name) {
const checkSyrupForPercentChar = data.name.includes('%')
const syrupReplacementName = data.name.replace('%', '')
history.push({
pathname: `saturation-directory/${data.id}/${urlFormat(
checkSyrupForPercentChar ? syrupReplacementName : data.name
)}`,
state: {
syrupData: data,
from: 'syrupDirectory'
}
})
}
}
重构前的代码:
function navigate(data: Partial<Saturation>) {
if (data.name) {
history.push({
pathname: `saturation-directory/${data.id}/${urlFormat(data.name)}`,
state: {
syrupData: data,
from: 'syrupDirectory'
}
})
}
}
要点是我合并的字符串函数以及路径名上的三元运算符。
因为我使用SSR使用
try {
decodeURIComponent(req.path)
} catch (error) {
res.redirect(encodeURIComponent(req.path))
return
}
解决了问题