使用Fetch API发POST请求遇JSON解析错误,请求状态却为200
问题描述
尝试通过Fetch API发送HTTP POST请求,前端代码如下:
const loginUser = () => { const name = (document.getElementById("email") as HTMLInputElement).value; const password = ( document.getElementById("password") as HTMLInputElement).value; fetch('http://localhost:8080/auth/login', { method: 'POST', mode:'cors', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ email: name, password: password }) }).then(response => { console.log(response.text); console.log(response);response.json()}) .then(json => console.log(json)) .catch(err => console.log(err)); }
请求返回状态码200,但JSON解析时触发错误:
ƒ text() { [native code] } Login.tsx:18 Response {type: 'cors', url: 'http://localhost:8080/auth/login', redirected: false, status: 200, ok: true, …}body: (...)bodyUsed: trueheaders: Headers {}[[Prototype]]: Headersok: trueredirected: falsestatus: 200statusText: ""type: "cors"url: "http://localhost:8080/auth/login"[[Prototype]]: Response Login.tsx:18 undefined VM5958:1 Uncaught (in promise) SyntaxError: Unexpected end of JSON input
后端返回代码:
HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.AUTHORIZATION, jwtToken); headers.add(HttpHeaders.CONTENT_TYPE,"application/json"); return ResponseEntity .ok() .headers(headers) .build();
疑问:为何出现该错误?是CORS阻塞了JSON解析吗?
问题分析与解决
这个错误和CORS无关——响应状态码200且type: 'cors'说明CORS配置正常,请求已成功到达后端并返回响应。
报错的核心原因是:后端设置了Content-Type: application/json响应头,但没有返回任何JSON格式的响应体。
当前后端代码用.build()返回了空响应体,前端调用response.json()时,会尝试把空内容解析成JSON,自然会抛出Unexpected end of JSON input错误。
修复方案
修改后端代码,返回合法的JSON响应体,比如返回包含token的对象:
HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.AUTHORIZATION, jwtToken); headers.add(HttpHeaders.CONTENT_TYPE,"application/json"); // 构造JSON响应体,示例返回token信息 Map<String, String> responseBody = new HashMap<>(); responseBody.put("token", jwtToken); return ResponseEntity .ok() .headers(headers) .body(responseBody);
如果确实不需要业务数据,至少返回空JSON对象{}避免解析失败:
return ResponseEntity .ok() .headers(headers) .body("{}");
另外,前端代码里console.log(response.text)存在小问题,response.text是方法,需调用response.text()才能获取内容,但这不是核心报错原因。
内容的提问来源于stack exchange,提问作者Johnyb
相关产品推荐
相关产品推荐

