Vue项目中Fetch请求含变量时自动拼接本地地址问题求助
问题:Vue项目Fetch请求拼接变量时URL被自动添加本地主机地址
在Vue项目中调用API时遇到问题:用变量projectId拼接请求URL时,Fetch会自动在URL前加上Vue应用的本地主机地址(如http://127.0.0.1:5173/);但直接硬编码projectId时,请求端点能正常工作。试过模板字符串${projectId}和字符串拼接+ projectId +两种方式,结果完全一致。
代码示例
const projectId = ref('') const uri = `"https://developer.api.autodesk.com/bim360/admin/v1/projects/b.${ projectId.value}/users"` function getUsers() { fetch (uri, requestOptions) .then(response => response.json()) .then((response) => { res.value = response }) .catch(error => console.log('error', error)) }
实际请求URL
实际发送的请求URL变成了:
http://127.0.0.1:5173/"https://developer.api.autodesk.com/bim360/admin/v1/projects/b.bfca3830-79e5-45c3-8ebe-0c3ba17273eb/users"
(注:上述projectId为示例,非真实ID)
解决思路
- 移除URL的多余双引号:你给
uri赋值时,错误地在URL前后加了双引号,导致Fetch把整个带引号的字符串当成相对路径,自动拼接本地主机地址。修正后的uri定义如下:const uri = `https://developer.api.autodesk.com/bim360/admin/v1/projects/b.${ projectId.value}/users` - 确保
projectId已赋值:因为projectId是ref对象,调用getUsers前要保证projectId.value有有效取值,避免生成b./users这类无效路径。可以在函数内增加判断:function getUsers() { if (!projectId.value) { console.log('请先设置projectId') return } const uri = `https://developer.api.autodesk.com/bim360/admin/v1/projects/b.${ projectId.value}/users` fetch(uri, requestOptions) .then(response => response.json()) .then((response) => { res.value = response }) .catch(error => console.log('error', error)) } - 将
uri定义移到函数内部:把uri的生成逻辑放到getUsers函数里,确保每次调用时都能获取到最新的projectId.value,而不是初始的空值。
内容的提问来源于stack exchange,提问作者Gosmith
相关产品推荐
相关产品推荐

