【发布时间】:2021-03-28 05:27:25
【问题描述】:
我有一个 fetch 函数,但是当我添加第二个参数时,它会抛出一个错误。但是如果我删除它,代码就会运行,所以,我不明白为什么它会抛出一个错误?我仍然想要第二个参数用于其他目的。
SyntaxError:JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符
我的代码
fetch("http://localhost:5000/PWA-order/menu", {
headers: {
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(responseData => console.log(responseData));
它会返回一个错误
但如果代码是
fetch("http://localhost:5000/PWA-order/menu")
.then(response => response.json())
.then(responseData => console.log(responseData));
响应成功
更新
如果第二个参数是“header”,它会工作,但如果第二个参数是“headers”,它会抛出一个错误”
fetch("http://localhost:5000/PWA-order/menu", {
header: {
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(responseData => console.log(responseData));
fetch("http://localhost:5000/PWA-order/menu", {
headers: {
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(responseData => console.log(responseData));
完整的功能是
const fetchAPI = async (url, bodyValue, method, jwt) => {
try {
const headers = {
'Content-Type': 'application/json',
'Authorization': jwt != null ? `Bearer ${jwt}` : null
}
const body = bodyValue ?? null;
const paramater = {
headers: headers,
method: method,
body
}
const response = await fetch(url, paramater);
const result = await response.json();
if(result){
return Promise.resolve(result);
}
else {
console.log('Error', response.status);
return Promise.reject(new Error(response.statusText));
}
}
catch(error){
console.log(error);
}
}
【问题讨论】:
-
而"second"参数是什么?
bodyValue还是parameter?而“第二个参数”的内容是什么? -
从完整的 fetch 函数中,第二个参数是一个名为参数的变量,它是一个返回 headers 对象、从参数中获取的方法对象和 body 对象的对象。忘了它。我感到困惑的是,当我从 fetch() 函数中添加第二个参数时,它会引发错误。例如,如果函数只是 fetch("localhost:5000/PWA-order/menu") .then(response => response.json()) .then(responseData => console.log(responseData)); 响应成功且没有错误,但是当我添加第二个参数(fetch(url, {header{}))。它会抛出一个错误
-
问题已更新。
标签: javascript json api promise fetch