"SyntaxError: token inesperado

En un componente de la aplicación React que maneja fuentes de contenido similares a Facebook, me encuentro con un error:

Feed.js: 94 undefined "parsererror "" SyntaxError: Unexpected token

Me encontré con un error similar que resultó ser un error tipográfico en el HTML dentro de la función de renderizado, pero ese no parece ser el caso aquí.

De forma más confusa, devolví el código a una versión anterior que funcionaba y todavía estoy recibiendo el error.

Feed.js:

import React from 'react';

var ThreadForm = React.createClass({
  getInitialState: function () {
    return {author: '', 
            text: '', 
            included: '',
            victim: ''
            }
  },
  handleAuthorChange: function (e) {
    this.setState({author: e.target.value})
  },
  handleTextChange: function (e) {
    this.setState({text: e.target.value})
  },
  handleIncludedChange: function (e) {
    this.setState({included: e.target.value})
  },
  handleVictimChange: function (e) {
    this.setState({victim: e.target.value})
  },
  handleSubmit: function (e) {
    e.preventDefault()
    var author = this.state.author.trim()
    var text = this.state.text.trim()
    var included = this.state.included.trim()
    var victim = this.state.victim.trim()
    if (!text || !author || !included || !victim) {
      return
    }
    this.props.onThreadSubmit({author: author, 
                                text: text, 
                                included: included,
                                victim: victim
                              })
    this.setState({author: '', 
                  text: '', 
                  included: '',
                  victim: ''
                  })
  },
  render: function () {
    return (
    <form className="threadForm" onSubmit={this.handleSubmit}>
      <input
        type="text"
        placeholder="Your name"
        value={this.state.author}
        onChange={this.handleAuthorChange} />
      <input
        type="text"
        placeholder="Say something..."
        value={this.state.text}
        onChange={this.handleTextChange} />
      <input
        type="text"
        placeholder="Name your victim"
        value={this.state.victim}
        onChange={this.handleVictimChange} />
      <input
        type="text"
        placeholder="Who can see?"
        value={this.state.included}
        onChange={this.handleIncludedChange} />
      <input type="submit" value="Post" />
    </form>
    )
  }
})

var ThreadsBox = React.createClass({
  loadThreadsFromServer: function () {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function (data) {
        this.setState({data: data})
      }.bind(this),
      error: function (xhr, status, err) {
        console.error(this.props.url, status, err.toString())
      }.bind(this)
    })
  },
  handleThreadSubmit: function (thread) {
    var threads = this.state.data
    var newThreads = threads.concat([thread])
    this.setState({data: newThreads})
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      type: 'POST',
      data: thread,
      success: function (data) {
        this.setState({data: data})
      }.bind(this),
      error: function (xhr, status, err) {
        this.setState({data: threads})
        console.error(this.props.url, status, err.toString())
      }.bind(this)
    })
  },
  getInitialState: function () {
    return {data: []}
  },
  componentDidMount: function () {
    this.loadThreadsFromServer()
    setInterval(this.loadThreadsFromServer, this.props.pollInterval)
  },
  render: function () {
    return (
    <div className="threadsBox">
      <h1>Feed</h1>
      <div>
        <ThreadForm onThreadSubmit={this.handleThreadSubmit} />
      </div>
    </div>
    )
  }
})

module.exports = ThreadsBox

En Chrome developer tools, el error parece provenir de esta función:

 loadThreadsFromServer: function loadThreadsFromServer() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function (data) {
        this.setState({ data: data });
      }.bind(this),
      error: function (xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },

Con la línea console.error(this.props.url, status, err.toString() subrayada.

Dado que parece que el error parece tener algo que ver con extraer datos JSON del servidor, intenté comenzar desde una base de datos en blanco, pero el error persiste. El error parece ser llamado en un bucle infinito presumiblemente como React continuamente intenta conectarse al servidor y, finalmente, se bloquea el navegador.

EDITAR:

He comprobado la respuesta del servidor con Chrome dev tools y Chrome cliente REST, y los datos parecen ser JSON adecuado.

EDITAR 2:

Parece que aunque el punto final de la API previsto está devolviendo los datos y el formato JSON correctos, React está sondeando http://localhost:3000/?_=1463499798727 en lugar del esperado http://localhost:3001/api/threads.

Estoy ejecutando un servidor webpack hot-reload en el puerto 3000 con la aplicación express ejecutándose en el puerto 3001 para devolver los datos del backend. Qué es frustrante aquí es que esto estaba funcionando correctamente la última vez que trabajé en él y no puedo encontrar lo que podría haber cambiado para romperlo.

Author: fragilewindows, 2016-05-17

20 answers

La redacción del mensaje de error corresponde a lo que obtiene de Google Chrome cuando ejecuta JSON.parse('<...'). Sé que dijiste que el servidor está configurando Content-Type:application/json, pero me hacen creer que la respuesta body es en realidad HTML.

Feed.js:94 undefined "parsererror" "SyntaxError: Unexpected token < in JSON at position 0"

Con la línea console.error(this.props.url, status, err.toString()) subrayada.

El err fue realmente lanzado dentro de jQuery, y se te pasó como una variable err. La razón por la que la línea está subrayada es simplemente porque es donde está registrando se.

Le sugeriría que agregue a su registro. Mirando las propiedades reales xhr (XMLHttpRequest) para obtener más información sobre la respuesta. Intente agregar console.warn(xhr.responseText) y lo más probable es que vea el HTML que se está recibiendo.

 99
Author: George Bailey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-17 15:49:59

Está recibiendo HTML (o XML) del servidor, pero dataType: json le está diciendo a jQuery que analice como JSON. Compruebe la pestaña" Red " en Chrome dev tools para ver el contenido de la respuesta del servidor.

 30
Author: nil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-17 15:29:43

Esto terminó siendo un problema de permisos para mí. Estaba tratando de acceder a una url para la que no tenía autorización con cancan, por lo que la url se cambió a users/sign_in. la url redirigida responde a html, no a json. El primer carácter en una respuesta html es <.

 7
Author: Andrew Shenstone,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-16 22:51:18

Experimenté este error "SyntaxError: Unexpected token m in JSON at position", donde el token 'm' puede ser cualquier otro carácter.

Resultó que me perdí una de las comillas dobles en el objeto JSON cuando estaba usando RESTconsole para la prueba de DB, como {"name: "math"}, la correcta debería ser {"name":"math"}

Me tomó mucho esfuerzo descubrir este error torpe. Me temo que otros se encontrarían con problemas similares.

 5
Author: VictorL,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-08 06:27:05

En mi caso el error fue el resultado de no asignar mi valor devuelto a una variable. Lo siguiente causó el mensaje de error:

return new JavaScriptSerializer().Serialize("hello");

Lo cambié a:

string H = "hello";
return new JavaScriptSerializer().Serialize(H);

Sin la variable, JSON no puede formatear correctamente los datos.

 3
Author: Versatile,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-27 17:06:04

En mi caso, estaba recibiendo este webpack en ejecución, y resultó ser algo de corrupción en algún lugar del dir local node_modules.

rm -rf node_modules
npm install

...fue suficiente para que funcionara bien de nuevo.

 3
Author: Kev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-07 12:43:05

Mi problema era que estaba recibiendo los datos de nuevo en un string que no estaba en un formato JSON adecuado, que estaba tratando de analizar. simple example: JSON.parse('{hello there}') dará un error en h. En mi caso la url de devolución de llamada estaba devolviendo un carácter innecesario antes de los objetos: employee_names([{"name":.... y estaba obteniendo un error en e en 0. Mi URL de devolución de llamada en sí tuvo un problema que cuando se solucionó, devolvió solo objetos.

 1
Author: Deke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-05 18:25:19

Este error ocurre cuando define la respuesta como application/json y obtiene un HTML como respuesta. Básicamente, esto sucedió cuando está escribiendo un script del lado del servidor para una url específica con una respuesta de JSON, pero el formato de error está en HTML.

 1
Author: sriram veeraghanta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-31 14:21:06

En mi caso, para un sitio de Azure hosted Angular 2/4, mi API llama a mySite/api/... estaba redirigiendo debido a problemas de enrutamiento de mySite. Por lo tanto, estaba devolviendo el HTML de la página redirigida en lugar de la api JSON. Agregué una exclusión en una web.archivo de configuración para la ruta de la api.

No estaba recibiendo este error al desarrollar localmente porque el Sitio y la API estaban en puertos diferentes. Probablemente hay una mejor manera de hacer esto ... pero funcionó.

<?xml version="1.0" encoding="UTF-8"?>

<configuration>
    <system.webServer>
        <rewrite>
        <rules>
        <clear />

        <!-- ignore static files -->
        <rule name="AngularJS Conditions" stopProcessing="true">
        <match url="(app/.*|css/.*|fonts/.*|assets/.*|images/.*|js/.*|api/.*)" />
        <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
        <action type="None" />
        </rule>

        <!--remaining all other url's point to index.html file -->
        <rule name="AngularJS Wildcard" enabled="true">
        <match url="(.*)" />
        <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
        <action type="Rewrite" url="index.html" />
        </rule>

        </rules>
        </rewrite>
    </system.webServer>
</configuration>
 1
Author: Dave,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-10 22:38:51

Esto podría ser viejo. Pero, simplemente ocurrió en angular, el tipo de contenido para la solicitud y la respuesta eran diferentes en mi código. Por lo tanto, compruebe los encabezados para,

 let headers = new Headers({
        'Content-Type': 'application/json',
        **Accept**: 'application/json'
    });

En React axios

axios({
  method:'get',
  url:'http://  ',
 headers: {
         'Content-Type': 'application/json',
        Accept: 'application/json'
    },
  responseType:'json'
})

JQuery Ajax:

 $.ajax({
      url: this.props.url,
      dataType: 'json',
**headers: { 
          'Content-Type': 'application/json',
        Accept: 'application/json'
    },**
      cache: false,
      success: function (data) {
        this.setState({ data: data });
      }.bind(this),
      error: function (xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
 1
Author: MPV,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-09 21:42:00

Tuve el mismo mensaje de error después de un tutorial. Nuestro problema parece ser ' url: this.apoyos.url ' en la llamada ajax. En React.DOM cuando estás creando tu elemento, el mío se ve así.

ReactDOM.render(
    <CommentBox data="/api/comments" pollInterval={2000}/>,
    document.getElementById('content')
);

Bueno, este cuadro de comentarios no tiene una url en sus accesorios, solo datos. Cuando cambié url: this.props.url -> url: this.props.data, hizo la llamada correcta al servidor y recuperé los datos esperados.

Espero que ayude.

 0
Author: Timea,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-21 09:55:10

Después de pasar mucho tiempo con esto, descubrí que en mi caso el problema era tener "homepage" definido en mi paquete.el archivo json hizo que mi aplicación no funcionara en firebase (el mismo error' token'). Creé mi aplicación react usando create-react-app, luego usé la guía de firebase en el READ.me archivo para implementar en las páginas de github, me di cuenta de que tenía que hacer un trabajo extra para que el enrutador funcione, y cambié a firebase. github guide había añadido la clave de la página de inicio en el paquete.json y causó el problema de implementación.

 0
Author: Alejandro B.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-06 16:58:56

Protip: Probando json en un nodo local.js server? Asegúrese de que no tiene ya algo enrutando a esa ruta

'/:url(app|assets|stuff|etc)';
 0
Author: dustintheweb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-25 20:31:01

En un nivel general, este error ocurre cuando se analiza un objeto JSON que tiene errores de sintaxis. Piense en algo como esto, donde la propiedad message contiene comillas dobles sin escapar:

{
    "data": [{
        "code": "1",
        "message": "This message has "unescaped" quotes, which is a JSON syntax error."
    }]
}

Si tiene JSON en su aplicación en algún lugar, entonces es bueno ejecutarlo a través de JSONLint para verificar que no tenga un error de sintaxis. Por lo general, este no es el caso, aunque en mi experiencia, por lo general es JSON regresó de una API que es el culpable.

Cuando una solicitud XHR es hecho a una API HTTP que devuelve una respuesta con un encabezado Content-Type:application/json; charset=UTF-8 que contiene JSON no válido en el cuerpo de la respuesta verá este error.

Si un controlador API del lado del servidor está manejando incorrectamente un error de sintaxis, y se está imprimiendo como parte de la respuesta, eso romperá la estructura de JSON devuelto. Un buen ejemplo de esto sería una respuesta API que contiene una Advertencia o Aviso de PHP en el cuerpo de respuesta:

<b>Notice</b>:  Undefined variable: something in <b>/path/to/some-api-controller.php</b> on line <b>99</b><br />
{
    "success": false,
    "data": [{ ... }]
}

El 95% de las veces esta es la fuente del problema para mí, y aunque está algo abordado aquí en las otras respuestas, no sentí que estuviera claramente descrito. Esperemos que esto ayude, si está buscando una manera práctica de rastrear qué respuesta de la API contiene un error de sintaxis JSON, he escrito un módulo Angular para eso.

Aquí está el módulo:

/**
 * Track Incomplete XHR Requests
 * 
 * Extend httpInterceptor to track XHR completions and keep a queue 
 * of our HTTP requests in order to find if any are incomplete or 
 * never finish, usually this is the source  of the issue if it's 
 * XHR related
 */
angular.module( "xhrErrorTracking", [
        'ng',
        'ngResource'
    ] )
    .factory( 'xhrErrorTracking', [ '$q', function( $q ) {
        var currentResponse = false;

        return {
            response: function( response ) {
                currentResponse = response;
                return response || $q.when( response );
            },
            responseError: function( rejection ) {
                var requestDesc = currentResponse.config.method + ' ' + currentResponse.config.url;
                if ( currentResponse.config.params ) requestDesc += ' ' + JSON.stringify( currentResponse.config.params );

                console.warn( 'JSON Errors Found in XHR Response: ' + requestDesc, currentResponse );

                return $q.reject( rejection );
            }
        };
    } ] )
    .config( [ '$httpProvider', function( $httpProvider ) {
        $httpProvider.interceptors.push( 'xhrErrorTracking' );
    } ] );

Se pueden encontrar más detalles en el artículo del blog al que se hace referencia anteriormente, no he publicado todo lo que se encuentra aquí, ya que probablemente no sea todo relevante.

 0
Author: Kevin Leary,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-07 20:37:23

Para mí, esto sucedió cuando una de las propiedades del objeto que estaba devolviendo como JSON lanzó una excepción.

public Dictionary<string, int> Clients { get; set; }
public int CRCount
{
    get
    {
        var count = 0;
        //throws when Clients is null
        foreach (var c in Clients) {
            count += c.Value;
        }
        return count;
    }
}

Añadiendo una comprobación nula, lo arreglé para mí:

public Dictionary<string, int> Clients { get; set; }
public int CRCount
{
    get
    {
        var count = 0;
        if (Clients != null) {
            foreach (var c in Clients) {
                count += c.Value;
            }
        }
        return count;
    }
}
 0
Author: Window,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-27 16:59:44

Solo algo básico para comprobar, asegúrese de que no tiene nada comentado en el archivo json

//comments here will not be parsed and throw error
 0
Author: Akin Hwan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-27 15:42:06

Solo para agregar a las respuestas, también sucede cuando su respuesta de API incluye

<?php{username: 'Some'}

Que podría ser un caso cuando su backend está usando PHP.

 0
Author: Tushar Sharma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-07 01:26:49

En python puedes usar json.Dump (str) antes de enviar el resultado a la plantilla html. con esta cadena de comandos convertir al formato json correcto y enviar a la plantilla html. Después de enviar este resultado a JSON.parse (resultado), esta es la respuesta correcta y puede usar esto.

 0
Author: user2713125,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-29 08:04:35

Para algunos, esto puede ayudarles chicos: Tuve una experiencia similar con Wordpress REST API. Incluso utilicé a Postman para comprobar si tenía las rutas o el punto final correctos. Más tarde descubrí que accidentalmente puse un " eco " dentro de mi script-hooks:

Depurar y comprobar su consola

Causa del error

Básicamente, esto significa que imprimí un valor que no es JSON que se mezcla con el script que causa el error AJAX - "SyntaxError: Unexpected token r in JSON en la posición 0 "

 0
Author: Ray Macz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-28 10:37:10

Token inesperado

Una solución simple a este error es escribir un comentario en el archivo styles.less.

 -4
Author: Dani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-05 20:10:58