我有一个获取函数,但是当我添加第二个参数时,它会抛出一个错误,但是如果我删除它,代码将会运行,所以,我不明白的是为什么它会抛出一个错误?我仍然想要第二个参数用于其他目的。
语法错误: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);
}
}
看起来响应不是 JSON 格式。尝试一下:
fetch("http://localhost:5000/PWA-order/menu", {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
})
.then(response => response.json())
.then(responseData => console.log(responseData));