[400에러] Unexpected token o in JSON at position 1 error
본문 바로가기

Network&etc/HTTP

[400에러] Unexpected token o in JSON at position 1 error

HTTP POST 전송도중 400에러와 SyntaxError에러를 만났다.

SyntaxError는 자바스크립트 문법에 맞지않는 문을 해석할 때 발생하는 에러 객체라고 한다.

400은 서버로보낸 요청이 잘못되었을때 생기는 에러라고한다.

 

JSON.parse도중에 발생한 에러인것을보니

JSON.stringify로보낸 객체를 parse하는 과정에서 발생한듯하였다.

 

웹브라우저에서 값이 어떻게 넘어가는지 디버깅을해보니

weather값과 count값관련하여

서버에서는 int를 원하지만 문자열로 넘어가는것을 확인하였다.

그래서 parseInt로 감싸 해결하였다.

async function setVote(type, value){
  const date = new Date().toUTCString()//utc
  await fetch('/vote/submit',{
    method:"POST",
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      match_id:voteDate.matchId,
      date:date,
      wallet: userAddress,
      vote_list:[{
        weather : parseInt(type)+1,	
        count : parseInt(value),
      }],
    }),
  })
  .catch(console.log)
}

참고

https://bobbyhadz.com/blog/javascript-unexpected-token-o-in-json-at-position-1#:~:text=The%20%22Unexpected%20token%20o%20in,convert%20a%20value%20to%20JSON.

 

Unexpected token o in JSON at position 1 error in JS | bobbyhadz

The "Unexpected token o in JSON at position 1" error occurs when we try to `JSON.parse` a value that is not a valid JSON string, e.g. a native JavaScript object. To solve the error, use the `JSON.stringify()` method if you need to convert a value to JSON.

bobbyhadz.com

 

반응형