简体   繁体   中英

How to parse the response of fetch as JSON

My react code:

fetch("http://localhost:8080/getnames")
  .then(response => response.text())
  .then(data => {
  alert("data: "+data);
  alert("index: "+data.indexOf(value));
  data.indexOf(value) === -1 ? callback() : callback("DuplicateName")
})

if array is ["abc","def"] then data.indexOf("a") is > -1 . Why? How to resolve this

What I want is exact match. how to accomplish that?

Instead of response.text() , you need to write response.json() to test for the exact match, since reponse.text() will give you data as string while, response.json() will return the data to be an array

fetch("http://localhost:8080/getnames")
  .then(response => response.json())
  .then(data => {
  alert("data: "+data);
  alert("index: "+data.indexOf(value));
  data.indexOf(value)===-1?callback():callback("DuplicateName")
})

If the response is JSON, you have to parse it. You should use response.json()<\/code> method instead of response.text()<\/code> :

fetch("http://localhost:8080/getnames")
  .then(response => response.json())
  .then(data => {
  alert("data: "+data);
  alert("index: "+data.indexOf(value));
  data.indexOf(value)===-1?callback():callback("DuplicateName")
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM