Javascript 访问JSON数据时出现基本错误(JS功能)
背景: 我正在尝试谷歌文档中给出的简单web推送通知示例(链接:) 我一直在JSON数据的第2行第1列遇到一个Javascript 访问JSON数据时出现基本错误(JS功能),javascript,json,object,ecmascript-6,es6-promise,Javascript,Json,Object,Ecmascript 6,Es6 Promise,背景: 我正在尝试谷歌文档中给出的简单web推送通知示例(链接:) 我一直在JSON数据的第2行第1列遇到一个SyntaxError:JSON.parse:unexpected字符,这意味着我做了一些根本错误的事情。我是JS新手,你能帮我吗 我订阅用户推送的简单功能是: function subscribeUserToPush() { const pub_key = document.getElementById("notif_pub_key"); const service_wor
SyntaxError:JSON.parse:unexpected字符,这意味着我做了一些根本错误的事情。我是JS新手,你能帮我吗
我订阅用户推送的简单功能是:
function subscribeUserToPush() {
const pub_key = document.getElementById("notif_pub_key");
const service_worker_location = document.getElementById("sw_loc");
return navigator.serviceWorker.register(service_worker_location.value)
.then(function(registration) {
const subscribeOptions = {
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(pub_key.value)
};
return registration.pushManager.subscribe(subscribeOptions);
})
.then(function(pushSubscription) {
sendSubscriptionToBackEnd(pushSubscription);
return pushSubscription;
});
}
sendSubscriptionToBackEnd()基本上使用fetch
如下:
function sendSubscriptionToBackEnd(subscription) {
const sub_obj = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'CSRFToken':get_cookie('csrftoken')
},
body: JSON.stringify(subscription)
}
return fetch('/subscription/save/', sub_obj)
.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.');
}
});
}
此操作失败,JSON数据的第2行第1列出现错误SyntaxError:JSON.parse:unexpected字符
执行console.log(sub_obj)
显示此对象:
Object { method: "POST", headers: {…}, body: "{\"endpoint\":\"https://updates.push.services.mozilla.com/wpush/v2/gAAAAABcaErG3Zn6Urzn5Hfhpyjl0eJg_IVtcgZI-sQr5KGE0WEWt9mKjYb7YXU60wgJtj9gYusApIJnObN0Vvm7oJFRXhbehxtSFxqHLOhSt9MvbIg0tQancpNAcSZ3fWA89E-W6hu0x4dqzqnxqP9KeQ42MYZnelO_IK7Ao1cWlJ41w8wZSlc\",\"keys\":{\"auth\":\"AJfXcUMO3ciEZL1DdD2AbA\",\"p256dh\":\"BN84oKD3-vFqlJnLU4IY7qgmPeSG96un-DttKZnSJhrFMWwLrH2j1a0tTB_QLoq5oLCAQql6hLDJ1W4hgnFQQUs\"}}" }
同时执行console.log(响应)
就在返回response.json()之前代码>显示:
Response { type: "basic", url: "http://127.0.0.1:8001/subscription/save/", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, body: ReadableStream, bodyUsed: false }
问题是什么?我该如何解决
将return-response.json()
更改为return-response.text()
,然后在responseData
上执行控制台日志,即可生成页面的整个HTML。最后出现了错误错误:服务器的响应不正确。
主要问题是CSRFToken
在sendsubscriptiontoken
中设置时标签错误。它应该是X-CSRFToken
。即
function sendSubscriptionToBackEnd(subscription) {
const sub_obj = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken':get_cookie('csrftoken'),
},
body: JSON.stringify(subscription)
}
return fetch('/subscription/save/', sub_obj)
.then(function(response) {
console.log(response);
if (!response.ok) {
throw new Error('Bad status code from server.');
}
return response.json();
})
.then(function(responseData) {
// response from the server
console.log(responseData)
if (!(responseData.data && responseData.data.success)) {
throw new Error('Bad response from server.');
}
});
}
那么为什么这会导致returnresponse.json()代码>失败
因为有问题的项目将未通过csrf检查的请求路由到默认视图,该视图根本不返回json响应。谜团解开了 主要问题是CSRFToken
在sendsubscriptiontokenbackend
中设置时被错误标记。它应该是X-CSRFToken
。即
function sendSubscriptionToBackEnd(subscription) {
const sub_obj = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken':get_cookie('csrftoken'),
},
body: JSON.stringify(subscription)
}
return fetch('/subscription/save/', sub_obj)
.then(function(response) {
console.log(response);
if (!response.ok) {
throw new Error('Bad status code from server.');
}
return response.json();
})
.then(function(responseData) {
// response from the server
console.log(responseData)
if (!(responseData.data && responseData.data.success)) {
throw new Error('Bad response from server.');
}
});
}
那么为什么这会导致returnresponse.json()代码>失败
因为有问题的项目将未通过csrf检查的请求路由到默认视图,该视图根本不返回json响应。谜团解开了 尝试执行return response.text()
,然后记录responseData
-听起来好像它没有给你JsonControl.log(response)
在response.json()之后,
give?@JackBashford它目前没有通过.json()
,因为反序列化失败,并且出现错误thrown@CertainPerformance:在问题末尾添加了您的建议结果谢谢,因此/subscription/save/
将向您发送HTML而不是JSON-听起来您应该查看(后端)代码处理/subscription/save/
尝试执行返回响应。text()
相反,然后记录responseData
-听起来好像它没有给你JSONWhat doesconsole.log(response)
afterresponse.json()
give?@JackBashford它目前没有通过.json()
,因为反序列化失败,并且出现错误thrown@CertainPerformance:在问题末尾添加了您的建议结果谢谢,因此/subscription/save/
将向您发送HTML而不是JSON-听起来您应该查看(后端)代码处理/subscription/save/