Javascript &引用;SyntaxError:意外标记<;在JSON中的位置0“;
在处理类似Facebook内容提要的React应用程序组件中,我遇到了一个错误: Feed.js:94位置0处JSON中未定义的“parsererror”语法错误:意外标记< 我遇到了一个类似的错误,结果是在render函数中的HTML中出现了一个输入错误,但这里的情况似乎不是这样 更让人困惑的是,我将代码回滚到了一个已知的早期工作版本,但仍然得到了错误 Feed.js:Javascript &引用;SyntaxError:意外标记<;在JSON中的位置0“;,javascript,json,reactjs,Javascript,Json,Reactjs,在处理类似Facebook内容提要的React应用程序组件中,我遇到了一个错误: Feed.js:94位置0处JSON中未定义的“parsererror”语法错误:意外标记url:this.props.data时,它正确地调用了服务器,我得到了预期的数据 我希望它能有所帮助。这对我来说是一个权限问题。我试图访问一个我没有cancan授权的url,因此该url被切换到用户/sign_in。重定向的url响应html,而不是json。html响应中的第一个字符是我的情况错误是由于我没有ass正在将我
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
行console.error(this.props.url,status,err.toString()
带下划线
由于错误似乎与从服务器提取JSON数据有关,我尝试从一个空白数据库开始,但错误仍然存在。错误似乎是在无限循环中调用的,可能是React不断尝试连接到服务器,最终导致浏览器崩溃
编辑:
我已经用Chrome开发工具和Chrome REST客户端检查了服务器响应,数据似乎是正确的JSON
编辑2:
看起来,尽管预期的API端点确实返回了正确的JSON数据和格式,但React正在轮询http://localhost:3000/?_=1463499798727
而不是预期的http://localhost:3001/api/threads
我正在端口3000上运行一个网页包热重新加载服务器,而express应用程序在端口3001上运行,以返回后端数据。令人沮丧的是,上次我处理它时,它工作正常,找不到可能更改的内容来破坏它。您收到的是HTML(或XML)从服务器返回,但是
数据类型:json
告诉jQuery将其解析为json。检查Chrome开发工具中的“网络”选项卡以查看服务器响应的内容。错误消息的措辞与运行json.parse时从Google Chrome获得的内容相对应(“在一个教程之后,我收到了相同的错误消息。我们的问题似乎是ajax调用中的“url:this.props.url”。在React.DOM中,当您创建元素时,我的问题是这样的
ReactDOM.render(
<CommentBox data="/api/comments" pollInterval={2000}/>,
document.getElementById('content')
);
ReactDOM.render(
,
document.getElementById('content')
);
嗯,这个评论框的道具中没有url,只有数据。当我切换url:this.props.url
->url:this.props.data
时,它正确地调用了服务器,我得到了预期的数据
我希望它能有所帮助。这对我来说是一个权限问题。我试图访问一个我没有cancan授权的url,因此该url被切换到用户/sign_in
。重定向的url响应html,而不是json。html响应中的第一个字符是我的情况错误是由于我没有ass正在将我的返回值初始化为变量。以下原因导致错误消息:
return new JavaScriptSerializer().Serialize("hello");
我把它改成:
string H = "hello";
return new JavaScriptSerializer().Serialize(H);
没有变量,JSON无法正确格式化数据。我的问题是,我以字符串
的形式获取数据,该字符串不是正确的JSON格式,然后我尝试对其进行解析。简单示例:JSON.parse({hello here})
将在h处出现错误。在我的例子中,回调url在对象前面返回了一个不必要的字符:员工姓名([{”姓名“:…
并在0处的e处出错。我的回调URL本身有一个问题,修复后只返回对象。在花了很多时间处理这个问题后,我发现问题是在我的package.json文件上定义了“homepage”,使我的应用程序无法在firebase上工作(相同的“token”错误)。
我使用create react app创建了我的react app,然后我使用READ.me文件上的firebase指南部署到github页面,意识到我必须做额外的工作才能让路由器工作,然后切换到firebase。github指南在package.json上添加了主页键,并导致了部署问题。在我的情况下,我得到了这个正在运行的网页包,并且结果是本地节点的某个地方出现了一些损坏
rm -rf node_modules
npm install
…足以让它再次正常工作。我遇到了这个错误“SyntaxError:位置处JSON中的意外标记m”,其中标记“m”可以是任何其他字符
事实证明,在使用RESTconsole进行DB测试时,我遗漏了JSON对象中的一个双引号,如{“name:”math“},正确的应该是{“name:”math“}
我花了很多精力才弄明白这个笨拙的错误。我担心其他人也会遇到类似的麻烦。Protip:在本地Node.js服务器上测试json?确保您还没有路由到该路径的东西
'/:url(app|assets|stuff|etc)';
为了补充答案,当您的API响应包括
<?php{username: 'Some'}
在我的例子中,对于Azure托管的Angular 2/4站点,由于mySite路由问题,我对mySite/API/…的API调用被重定向。因此,它从重定向页面返回HTML,而不是API JSON。我在web.config文件中为API路径添加了一个排除项
我在本地开发时没有遇到这个错误,因为站点和API在不同的端口上。可能有更好的方法来做到这一点…但它起了作用
<?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>
在一般级别上,当解析包含语法错误的JSON对象时,会发生此错误。请考虑类似的情况,其中message属性包含未转换的双引号:
{
"data": [{
"code": "1",
"message": "This message has "unescaped" quotes, which is a JSON syntax error."
}]
}
如果你的应用程序中某处有JSON,那么最好运行它来验证它没有语法错误。通常情况并非如此,但根据我的经验,通常是从API返回的JSON才是罪魁祸首
当向HTTP API发出XHR请求时,该请求返回一个带有内容类型的响应:application/json;charset=UTF-8<
{
"data": [{
"code": "1",
"message": "This message has "unescaped" quotes, which is a JSON syntax error."
}]
}
<b>Notice</b>: Undefined variable: something in <b>/path/to/some-api-controller.php</b> on line <b>99</b><br />
{
"success": false,
"data": [{ ... }]
}
/**
* 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' );
} ] );
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;
}
}
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;
}
}
//comments here will not be parsed and throw error
let headers = new Headers({
'Content-Type': 'application/json',
**Accept**: 'application/json'
});
axios({
method:'get',
url:'http:// ',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
responseType:'json'
})
$.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)
});
},
homepage: "www.example.com"
hompage: ""
var string = "some string";
JSON.parse(string)
var invalidJSON= '{"foo" : "bar", "missedquotehere : "value" }';
JSON.parse(invalidJSON)
VM598:1 Uncaught SyntaxError: Unexpected token v in JSON at position 36
var validJSON= '{"foo" : "bar", "missedquotehere : "value" }';
JSON.parse(validJSON)
'/theRouteIWant&someVar=Some value to send'
'/theRouteIWant?someVar=Some value to send'
^
SyntaxError: Unexpected token < in JSON at position 0 in _generated_background_page.html