Javascript React.js:Uncaught(in promise)语法错误:JSON输入意外结束
在尝试添加新项时,我收到一个错误“Body.js:22 Uncaught(in promise)SyntaxError:Unexpected end of JSON input”。作为后端,我使用RubyonRails 当我试图在控制台日志中保存数据时,它工作正常,所以数据传输正常Javascript React.js:Uncaught(in promise)语法错误:JSON输入意外结束,javascript,json,reactjs,Javascript,Json,Reactjs,在尝试添加新项时,我收到一个错误“Body.js:22 Uncaught(in promise)SyntaxError:Unexpected end of JSON input”。作为后端,我使用RubyonRails 当我试图在控制台日志中保存数据时,它工作正常,所以数据传输正常 import React from 'react' import AllProducts from './AllProducts' import NewProduct from './NewProduct';
import React from 'react'
import AllProducts from './AllProducts'
import NewProduct from './NewProduct';
class Body extends React.Component {
constructor(props) {
super(props);
this.state = {
products: []
};
this.handleFormSubmit = this.handleFormSubmit.bind(this)
this.addNewProduct = this.addNewProduct.bind(this)
}
handleFormSubmit(title, body,price){
let productbody = JSON.stringify({product: {title: title, body:body,price: price} })
fetch('http://localhost:3000/admin/products', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: productbody,
}).then((response) => {return response.json()})
.then((product)=>{this.addNewProduct(product)})
}
addNewProduct(product){
this.setState({
products: this.state.products.concat(product)
})
}
componentDidMount(){
fetch('/admin/products.json')
.then((response) => {return response.json()})
.then((data) => {this.setState({ products: data }) });
}
render(){ console.log('I was triggered during render')
return(
<div>
<NewProduct handleFormSubmit={this.handleFormSubmit} />
<AllProducts products={this.state.products} />
</div>
)
}
}
export default Body
格式有问题吗?但是我需要做什么呢
返回了什么?第22行是哪一行?这里要做的第一件事是查看浏览器控制台的“网络”选项卡,查看对
fetch
的响应是什么(如果您发布了关于它的问题,请将其包括在内:-))。你的代码是开放的(不仅仅是你,很多代码都是开放的),因此你可能试图将一些东西解析为JSON而不是JSON。@t.J.Crowder添加了网络选项卡的屏幕,请看,如果这是实际内容,它不是JSON;JSON在引号中的属性名称周围有引号。请将代码、错误消息、标记等作为文本而不是文本图片发布。原因:另外,您所展示的是对发回内容的解释版本,而不是实际发回的内容。要查看实际返回的内容,请单击该面板上显示的“查看源”链接。
import React from 'react'
const NewProduct = (props) => {
let formFields = {}
return(
<form onSubmit={ (e) => {
e.preventDefault();
props.handleFormSubmit(
formFields.title.value,
formFields.body.value,
formFields.price.value
);
e.target.reset();}
}>
<input ref={input => formFields.title = input} placeholder='Enter the name of the item'/>
<input ref={input => formFields.body = input} placeholder='Enter a description' />
<input ref={input => formFields.price = input} placeholder='Enter a price' />
<button>Submit</button>
</form>
)
}
export default NewProduct
:}).then((response) => {return response.json()})