Giphy上传使用jQuery .ajax正常但fetch返回401错误如何解决
问题原因
- 原生
fetch不会像jQuery的$.ajax一样自动序列化普通对象类型的请求参数,你直接将参数对象传给body时,对象会被转为[object Object]字符串,服务器无法解析到api_key字段,因此返回401未授权错误。 $.ajax传入对象类型的data时,会自动将其序列化为application/x-www-form-urlencoded格式的请求体,同时自动设置对应请求头,因此可以正常鉴权。
修复方案
方案1:使用URLSearchParams序列化参数(匹配jQuery默认行为)
fetch("https://upload.giphy.com/v1/gifs", { method: "POST", body: new URLSearchParams({ api_key: "E0sxxxxxxxxxxxxxxxxxxxxxxxxxx", source_image_url: "https://urlto/snoopy.gif", tags: "cute dog", }) }).then((response) => { console.log("status:", response); return response.json(); }).then(data => { console.log(data); }).catch(err => { alert("fail"); })
方案2:使用FormData传递参数(适合后续扩展上传本地文件)
const formData = new FormData(); formData.append('api_key', 'E0sxxxxxxxxxxxxxxxxxxxxxxxxxx'); formData.append('source_image_url', 'https://urlto/snoopy.gif'); formData.append('tags', 'cute dog'); fetch("https://upload.giphy.com/v1/gifs", { method: "POST", body: formData }).then(response => response.json()) .then(data => console.log(data)) .catch(() => alert('fail'));
方案3:参数放入查询字符串
const params = new URLSearchParams({ api_key: "E0sxxxxxxxxxxxxxxxxxxxxxxxxxx", source_image_url: "https://urlto/snoopy.gif", tags: "cute dog", }); fetch(`https://upload.giphy.com/v1/gifs?${params}`, { method: "POST" }).then(response => response.json()) .then(data => console.log(data)) .catch(() => alert('fail'));
以上三种方案都可以正常通过鉴权,如需后续上传本地二进制GIF文件,优先选择FormData方案。
内容的提问来源于stack exchange,提问作者user82384
相关产品推荐
相关产品推荐

