Syntaxerror: Unexpected token < in JSON at position 0

Asked

Viewed 5,128 times

0

I’m trying to file a requisition HTTP for a API and I get the following error:

Uncaught (in Promise) Syntaxerror: Unexpected token < in JSON at position 0

  • Why is this happening error?
  • How to treat XML in the components of React?

Call to API:

  plotarCamadaNoMapa(camadas) {
        fetch('api/TelaOperadorRJ/GetXMLCamada?idCamada=' + camadas)
            .then(response => response.json())
            .then(data => {
                this.setState({
                    xmlCamada: data

                });
            });


        console.log(this.state.xmlCamada);     
    }

Filing cabinet XML:

<kml xmlns="http://www.opengis.net/kml/2.2">
  <Document>
    <Style id="Style1">
      <LineStyle>
        <color>ff000000</color>
        <width>1.2</width>
      </LineStyle>
      <PolyStyle>
        <color>8000ffff</color>
        <fill>true</fill>
        <outline>true</outline>
      </PolyStyle>
    </Style>
    <Placemark>
      <name>Polígono 0</name>
      <styleUrl>#Style1</styleUrl>
      <Polygon>
        <outerBoundaryIs>
          <LinearRing>
            <coordinates>-46.878889999999998,-23.54439
-46.843359999999997,-23.52
-46.837859999999999,-23.516220000000001
-46.812629999999999,-23.522829999999999
-46.808340000000001,-23.54007
-46.797870000000003,-23.563590000000001
-46.814169999999997,-23.57067
-46.850740000000002,-23.56831
-46.878889999999998,-23.54439</coordinates>
          </LinearRing>
        </outerBoundaryIs>
      </Polygon>
    </Placemark>
  </Document>
</kml>
  • 2

    Dear Igor just remove the .then(response => response.json()), XML is not JSON, so there’s no way he can interpret this

  • It even worked, but went into an infinite looping.

  • Probably wrong somewhere else dear Igor

1 answer

2


I believe the server’s response body is not Content-Type:application/json, this does not affect the manipulation of the data received, but in my opinion it is a mistake for the backend not to notify you the true type of content that will be received (even for security reasons), because the Content-Type tells the customer what kind of content the answer actually has...

But your real problem as said above, you’re probably not getting content like JSON, with this you are trying to force a conversion that can not, in this case you are trying to pass a content received from the server of type HTML or XML for JSON, therefore is generated the error.

To find out what kind of content you’re receiving from the server, do the following:

Mark the tab "Network" in the tools of Chrome Dev to see the content type of the server response, or debug using this code:

.then(function(response) {
    console.log(response);
    console.log(response.status);
    console.log(response.json());
    console.log(response.text());
}).catch(function(err) {  
       console.log('Fetch Error :-S', err);  
});

To correctly manipulate the content XML received, follow the instructions:

  • 1) Remove the response.json()
  • 2) To transform content of type text in XML in the React, you can use the library React-xml-parser.

How to use the library react-xml-parser?

Using this XML as an example:

<?xml version='1.0' encoding='utf-8'?>
<Library>
   <Books count='1'>
       <Book id='1'>
           <Name>Me Before You</Name>
           <Author>Jojo Moyes</Author>
       </Book>
   </Books>
   <Music count=1>
       <CD id='2'>
           <Name>Houses of the Holy</Name>
           <Artist>Led Zeppelin</Artist>
       </CD>
   </Music>
</Library>

Step 1): Install it with the command below in your terminal:

npm i react-xml-parser

Step 2): Use the code below the library to convert content of type text for XML and can manipulate the same.

var XMLParser = require('react-xml-parser');
var xml = new XMLParser().parseFromString(xmlText);
console.log(xml);
console.log(xml.getElementsByTagName('Name'));

Methods that are currently supported by the library:

parseFromString(string): Returns an object XML as described in the output example representing the input text.

toString(objeto XML): returns the text representation of a XML incoming.

getElementsByTagName(string): Returns all tags with the same name as the method input string (no case differentiation). for all possible tags, use '*' as input.

Note

Add the code of step (2) within your .then(), replace the xmlText for his response and use the xml.getElementsByTagName('nomeDaTag') according to your scenario.

  • 2

    Dear Thiago, the Content-Type is indifferent, the problem is trying to force the content in . json() when the content is a text file in xml format, you can put the content-type you want, the content will be the same and will not work.

  • @Guilhermenascimento I understand and asserted this also in reply, but in my opinion the backend is wrong in not declaring the Content-Type of the right kind, because the Content-Type tells the client what kind of content the answer is, in fact. For less experienced developers as is the case here, he had difficulty because of perhaps the Content-Type not being correct (I don’t know if he analyzed it too), finally for you and I who have experience, we wouldn’t get to the point of forcing a text file in xml format for json. If you want me to apply modification let me know.

  • @THIAGODEBONIS please show the example forcing text in xml format to json, I want to see all strands in this process.

  • 1

    @Igorcarreiro is fine for you?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.