使用nodejs将ReactJs连接到mysql时遇到问题。 这是我的完整代码。
这是我的React文件'member.js',在端口3000上运行。
import React, { Component } from 'react';
class Member extends Component {
constructor() {
super();
this.state = { player: {} };
this.onSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
var self = this;
fetch('/player', {
method: 'GET',
data: {
number: self.refs.number,
name: self.refs.name,
position: self.refs.position
}
}).then(function(response) {
return response.json();
}).then(function(body) {
console.log(body);
});
}
render() {
return (
<div className="member-page">
<form onSubmit={this.onSubmit}>
<input type="text" placeholder="Number" ref="number" />
<input type="text" placeholder="Name" ref="name" />
<input type="text" placeholder="Position" ref="position" />
<input type="submit" />
</form>
</div>
)
}
}
export default Member;
这是我的节点文件'player.js',在端口4000上运行。
var http = require('http');
var mysql = require('mysql');
var express = require('express');
var app = express();
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "react_1"
});
app.post('/player', function(req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
// Get sent data.
var player = req.body;
// Do a MySQL query.
var query = connection.query('INSERT INTO player VALUES ?', player, function(err, result) {
// Neat!
});
res.end('Success');
});
app.listen(4000, function() {
console.log('Example app listening on port 4000!');
});
当我尝试输入数据时,我得到的错误是'未捕获(在承诺中)语法错误:在位置0的JSON中出现意外的令牌S',我不知道为什么,2天后我必须再次向我的讲座展示这个职责,请有人帮我解决这个问题。
非常感谢你。答案 0 :(得分:0)
首先,你得到那个错误?
然后,您是否可以在构建JSON有效内容时尝试向您的react脚本添加引号
data : {
"number" : self.refs.number,
"name" : self.refs.name,
"position" : self.refs.position,
}
然后,确保在标题上将Content-Type设置为application / json:
&#39;内容类型&#39;:&#39; application / json&#39;