[英]Parsing in JS gets me a SyntaxError: JSON.parse: unexpected character
當我嘗試解析 JSON 對象時會彈出一個錯誤(或者至少我猜它應該是一個對象,因為響應的標題中有"content-type": "application/json
)。這是我得到的完整錯誤堆棧:
Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
handleUpdate index.jsx:55
UserUpdateForm index.jsx:77
React 5
unstable_runWithPriority scheduler.development.js:468
React 3
workLoop scheduler.development.js:417
flushWork scheduler.development.js:390
performWorkUntilDeadline scheduler.development.js:157
js scheduler.development.js:180
js scheduler.development.js:644
__require chunk-HV27UI33.js:9
js index.js:6
__require chunk-HV27UI33.js:9
React 2
__require chunk-HV27UI33.js:9
js React
__require chunk-HV27UI33.js:9
<anonymous> react-dom:1
index.jsx:55:24
從這段代碼:
const handleUpdate = async ({ username, email }) => {
const token = Cookies.get("token");
const body = { user: { username: username, email: email } };
const res = await update(`/users/${currentUser.id}`, body, token);
const response = JSON.parse(res);
console.log(response);
if (response.status === 200) {
handleChange(response);
}
};
其中update()
是:
import axios from 'axios';
import { BASE_URL } from "./config.js";
const update = async (
endpoint,
body = null,
jwt_token = null,
header = { "Content-Type": "application/json" }) => {
let opt = header;
if (jwt_token){
opt["Authorization"] = jwt_token
}
try {
return await axios.patch(BASE_URL + endpoint, body, { headers: opt })
} catch (err) {
console.error(`An error occurred while trying to fetch ${endpoint}. ${err}`);
}
}
export default update;
我已經找到了類似問題的答案,談到了未以 UTF-8 編碼的數據問題,但我認為這不是我的情況。 真正奇怪的是,我對使用類似請求的其他組件沒有這樣的問題(我構建了非常相似的post
請求,並且不會在使用它們的組件中產生任何問題)。 如果我不解析從服務器獲得的響應, response.data.attributes
將是undefined
,即使有鍵data
和attributes
。
編輯:這是響應的標題。 我們可以看到,有一個參數content-type: application/json
:
HTTP/2 200 OK
server: nginx
date: Tue, 20 Jul 2021 09:02:11 GMT
content-type: application/json; charset=utf-8
x-sso-wat: You've just been SSOed
access-control-allow-origin: *
access-control-allow-methods: GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD
access-control-expose-headers:
access-control-max-age: 7200
x-frame-options: SAMEORIGIN
x-xss-protection: 1; mode=block
x-content-type-options: nosniff
x-download-options: noopen
x-permitted-cross-domain-policies: none
referrer-policy: strict-origin-when-cross-origin
etag: W/"***
cache-control: max-age=0, private, must-revalidate
x-request-id: ***
x-runtime: 0.053418
vary: Origin
content-security-policy: upgrade-insecure-requests
content-security-policy-report-only: default-src https: data: 'unsafe-inline' 'unsafe-eval'
permissions-policy: interest-cohort=()
strict-transport-security: max-age=63072000; includeSubDomains; preload
X-Firefox-Spdy: h2
編輯 2:正如另一個 Stackoverflow 線程中所建議的,我試圖解析一個字符串化的響應。 感覺就像是在惡作劇 JS,但還好,它避免了“JSON.parse:意外字符”問題。 含義:初始響應是一個 JSON 對象,但我仍然無法訪問response.data.attributes
...這太神奇了。
axios 會自動解析響應,因此它已經是一個對象。 該錯誤來自嘗試解析不是字符串而是對象的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.