本文介绍了未捕获(承诺)SyntaxError:意外令牌<在JSON中的位置0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试创建注册页面并将数据发送到mysql db.我只是写了这段代码.server.js
I try to create signup page and send data to mysql db. I just wrote this codes..server.js
var mysql = require('mysql');
var http = require('http');
var port = process.env.PORT || 1337;
var con = mysql.createConnection({
host: "localhost",
user: "*****",
password: "*******",
database: "node"
});
con.connect(function (error) {
app.post('/', function (req, res) {
var user = req.body;
var query = connection.query('INSERT INTO signup(FirstName, LastName, Email,Password, PasswordConfirm) SET ?', user, function (err, result) {
});
res.end('Success');
});
});
app.js,这是我的组件.
app.js this is my component.
class Signup extends React.Component {
constructor() {
super();
this.state = { user: {} };
this.onSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
var self = this;
fetch('/', {
method: 'POST',
data: {
firstname: self.refs.FirstName,
lastname: self.refs.LasttName,
email: self.refs.Email,
password: self.refs.Password,
passwordconfirm: self.refs.PasswordConfirm
}
})
.then(function(response) {
return response.json()
}).then(function(body) {
console.log(body);
});
}
render(){
return(
<div>
<form id="signup" onSubmit={this.onSubmit}>
<input type="text" id="firstName" placeholder="FirstName" ref="firstname"/>
<input type="text" id="lastName" placeholder="LastName" ref="lastname"/>
<input type="email" id="email" placeholder="Email" ref="email"/>
<input type="password" id="password" placeholder="Password" ref="password" />
<input type="password" id="confirm" placeholder="PasswordConfirm"ref="passwordconfirm" />
<input type="submit" />
</form>
</div>
)
}}
我只是尝试将数据发送到mysql db.我收到此错误消息->未捕获(承诺)SyntaxError:意外令牌<在JSON中的位置0
I just try to send data to mysql db.I got this error message -->Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
为什么?怎么了?
推荐答案
可能是您的响应正文为html,请尝试在jSON中对其进行解析,并尝试将标头添加为
May be your response body is html,try to parse it in jSON and also try to add headers as
fetch('/', {
method: 'POST',
data: {
firstname: self.refs.FirstName,
lastname: self.refs.LasttName,
email: self.refs.Email,
password: self.refs.Password,
passwordconfirm: self.refs.PasswordConfirm
},
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(function(response) {
console.log(response);
return response.json();
})
.then(function(body) {
console.log(body);
});
这篇关于未捕获(承诺)SyntaxError:意外令牌<在JSON中的位置0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!