codestates / codestates/conimals
[정새얀] 220612 Error - Handling
- Dominant language
- JavaScript
- Stars
- 3
- Forks
- 5
- PR merge metrics
- No merged PRs in 30d
Description
> 해결된 에러라면 라벨에 'Complete' 를 달아주세요.
> 미해결된 에러라면 라벨을 'In progress' 로 변경해주세요.
### 어떤 에러인가요?
- 게시글 작성 후 내용을 확인하려 했을 때 콘솔에 promise syntax error 메시지를 확인함.
### 에러 메시지
```bash
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
```
### 에러 핸들링 방법
- 원래 클라이언트의 View.js코드에 없던 method와 headers에 application/json을 추가해주고, 그 내용을 const 상수화를 시켜주었다.
+) 레퍼런스 링크를 보고 고쳐주었는데, 바꾼 코드로 적용하고 난 후의 코드에서
await fetch(`http://localhost:8080/posts/${id}`)를 적용해보니 동일한 에러 메시지가 콘솔에 찍히는 것을 확인할 수 있었다.
await fetch(`http://localhost:8080/posts/view/${id}`)로 고쳐주었을 때 나오지 않았다.
```js
// 제일 처음에 작성한 코드
const getDetail = async () => {
const json = await (
await fetch(`http://localhost:8080/posts/${id}`)
).json();
setSelectedPost(json.data);
};
```
```js
// 1차 수정 코드
const getDetail = async () => {
const config = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
};
const json = await (
await fetch(`http://localhost:8080/posts/view/${id}`, config)
).json();
setSelectedPost(json.data);
};
```
```js
// 2차 수정 코드
// config를 없애고 /view를 추가함
const getDetail = async () => {
const json = await (
await fetch(`http://localhost:8080/posts/view/${id}`)
).json();
setSelectedPost(json.data);
};
```
### 에러 핸들링을 위해 참고한 레퍼런스 링크
[레퍼런스1](https://velog.io/@rain98/syntaxerror-unexpected-token-in-json-at-position-0-%EC%97%90%EB%9F%AC-%EC%98%A4%EB%A5%98-%ED%95%B4%EA%B2%B0-%EB%B0%A9%EB%B2%95)
[레퍼런스2](https://zivvle.tistory.com/entry/%EC%97%90%EB%9F%AC-Uncaught-in-promise-SyntaxError-Unexpected-token-in-JSON-at-position-0?category=934563)
[스택오버플로우 레퍼런스](https://stackoverflow.com/questions/37269808/react-js-uncaught-in-promise-syntaxerror-unexpected-token-in-json-at-posit)
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.