Javascript Uncaught (in promise) SyntaxError: Unexpected end of JSON input
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43362431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught (in promise) SyntaxError: Unexpected end of JSON input
提问by zoltar
I am trying to send a new push subscription to my server but am encountering an error "Uncaught (in promise) SyntaxError: Unexpected end of JSON input" and the console says it's in my index page at line 1, which obviously is not the case.
我正在尝试向我的服务器发送一个新的推送订阅,但遇到错误“未捕获(承诺)SyntaxError:JSON 输入的意外结束”并且控制台说它在我的索引页中的第 1 行,这显然不是这种情况.
The function where I suspect the problem occurring (because error is not thrown when I comment it out) is sendSubscriptionToBackEnd(subscription)which is called in the following:
我怀疑发生问题的函数(因为当我注释掉它时没有抛出错误)是sendSubscriptionToBackEnd(subscription)在下面调用的:
function updateSubscriptionOnServer(subscription) {
const subscriptionJson = document.querySelector('.js-subscription-json');
const subscriptionDetails = document.querySelector('.js-subscription-details');
if (subscription) {
subscriptionJson.textContent = JSON.stringify(subscription);
sendSubscriptionToBackEnd(subscription);
subscriptionDetails.classList.remove('is-invisible');
} else {
subscriptionDetails.classList.add('is-invisible');
}
}
The function itself (which precedes the above function):
函数本身(在上述函数之前):
function sendSubscriptionToBackEnd(subscription) {
return fetch('/path/to/app/savesub.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(subscription)
})
.then(function(response) {
if (!response.ok) {
throw new Error('Bad status code from server.');
}
return response.json();
})
.then(function(responseData) {
if (!(responseData.data && responseData.data.success)) {
throw new Error('Bad response from server.');
}
});
}
I have tried replacing single quotes with double quotes in the fetch call but that yields the same results.
我尝试在 fetch 调用中用双引号替换单引号,但产生相同的结果。
I know that the JSON should be populated because it prints to the screen in the updateSubscriptionOnServer()function with subscriptionJson.textContent = JSON.stringify(subscription);, and I used that output in the google codelab's example server to receive a push successfully.
我知道 JSON 应该被填充,因为它在updateSubscriptionOnServer()函数中打印到屏幕上subscriptionJson.textContent = JSON.stringify(subscription);,并且我在 google codelab 的示例服务器中使用了该输出来成功接收推送。
EDIT: Here is the JSON as a string, but I don't see a mistake in syntax:
编辑:这是作为字符串的 JSON,但我没有看到语法错误:
{"endpoint":"https://fcm.googleapis.com/fcm/send/dLmthm1wZuc:APA91bGULRezL7SzZKywF2wiS50hXNaLqjJxJ869y8wiWLA3Y_1pHqTI458VIhJZkyOsRMO2xBS77erpmKUp-Tg0sMkYHkuUJCI8wEid1jMESeO2ExjNhNC9OS1DQT2j05BaRgckFbCN","keys":{"p256dh":"BBz2c7S5uiKR-SE2fYJrjPaxuAiFiLogxsJbl8S1A_fQrOEH4_LQjp8qocIxOFEicpcf4PHZksAtA8zKJG9pMzs=","auth":"VOHh5P-1ZTupRXTMs4VhlQ=="}}
Any ideas??
有任何想法吗??
回答by Max Cabrera
This might be a problem with the endpoint not passing the appropriate parameters in the response's header.
这可能是端点未在响应标头中传递适当参数的问题。
In Chrome's console, inside the Network tab, check the headers sent by the endpoint and it should contain this: Example of proper response to allow requests from localhost and cross domains requests
在 Chrome 控制台的 Network 选项卡中,检查端点发送的标头,它应该包含以下内容: 允许来自本地主机和跨域请求的正确响应示例
Ask the API developer to include this in the headers:
要求 API 开发人员将其包含在标头中:
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials" : true
回答by Kai Durai
For someone looking here later. I received this error not because of my headers but because I was not recursively appending the response body to a string to JSON.parse later.
对于稍后看这里的人。我收到此错误不是因为我的标头,而是因为我稍后没有将响应主体递归地附加到 JSON.parse 的字符串中。
As per the MDN example(I've taken out some parts of their example not immediately relevant):
根据MDN 示例(我删除了他们示例中不立即相关的某些部分):
reader.read().then(function processText({ done, value }) {
if (done) {
console.log("Stream complete");
return;
}
result += chunk;
return reader.read().then(processText);
});
For my issue I had to
对于我的问题,我不得不
- Use a named function (not an anonymous ()=>{}) inside the .then
- Append the result together recursively.
- Once done is true execute something else on the total appended result
- 在 .then 中使用命名函数(不是匿名 ()=>{})
- 将结果递归地附加在一起。
- 一旦完成,对总附加结果执行其他操作
Just in case this is helpful for you in the future and your issue is not header related, but related to the done value not being true with the initial JSON stream response.
以防万一这对您将来有帮助,并且您的问题与标头无关,而是与初始 JSON 流响应中的 done 值不正确有关。

