将数据从React发送到MySQL
我正在创建一个发布应用程序,该应用程序需要使用React和MySQL数据库之间的通信来回发送信息.使用Express作为我的JS服务器.服务器代码如下:
I am creating a publishing application that needs to use communication between React and MySQL database to send information back and forth. Using Express as my JS server. The server code looks as follows:
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const cors = require('cors');
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'ArticleDatabase',
port: 3300,
socketPath: '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock'
});
// Initialize the app
const app = express();
app.use(cors());
appl.post('/articletest', function(req, res) {
var art = req.body;
var query = connection.query("INSERT INTO articles SET ?", art,
function(err, res) {
})
})
// https://expressjs.com/en/guide/routing.html
app.get('/comments', function (req, res) {
// connection.connect();
connection.query('SELECT * FROM articles', function (error, results,
fields) {
if (error) throw error;
else {
return res.json({
data: results
})
};
});
// connection.end();
});
// Start the server
app.listen(3300, () => {
console.log('Listening on port 3300');
});
我的React类如下:
And my React class looks as follows:
class Profile extends React.Component {
constructor(props) {
super(props);
this.state = {
title: '',
author: '',
text: ''
}
}
handleSubmit() {
// On submit of the form, send a POST request with the data to the
// server.
fetch('http://localhost:3300/articletest', {
body: JSON.stringify(this.state),
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'content-type': 'application/json'
},
method: 'POST',
mode: 'cors',
redirect: 'follow',
referrer: 'no-referrer',
})
.then(function (response) {
console.log(response);
if (response.status === 200) {
alert('Saved');
} else {
alert('Issues saving');
}
});
}
render() {
return (
<div>
<form onSubmit={() => this.handleSubmit()}>
<input type = "text" placeholder="title" onChange={e =>
this.setState({ title: e.target.value} )} />
<input type="text" placeholder="author" onChange={e =>
this.setState({ author: e.target.value} )} />
<textarea type="text" placeholder="text" onChange={e =>
this.setState({ text: e.target.value} )} />
<input type="Submit" />
</form>
</div>
);
}
}
我在在线教程中找到了相当标准的东西.我可以搜索我的数据库并显示获取的信息没有问题,但是反之则不行.当我尝试从<form>
标记获取输入时,没有任何内容插入到数据库中,而是出现了此错误:
So fairly standard stuff that I found in online tutorials. I can search my database and display fetched info no problem, but not the other way around. When I try to take input from the <form>
tag nothing is inserted into my database but instead I get this error:
[Error] Fetch API cannot load
http://localhost:3000/static/js/0.chunk.js due to access control
checks.
Error: The error you provided does not contain a stack trace.
Unhandled Promise Rejection: TypeError: cancelled
我知道这与访问控制有关,但是由于我已经在使用cors并且可以成功地从数据库中检索数据,所以我不确定自己在做什么错.任何建议将不胜感激.预先谢谢你.
I understand that this has something to do with access control but since I am already using cors and can successfully retrieve data from the database, I am not sure what I am doing wrong. Any suggestions will be greatly appreciated. Thank you in advance.
您需要首先验证您的服务点已启用CORS,以找出问题所在.为了仅专注于CORS功能,我将暂时删除MySQL代码.
You'll need to isolate the problem by first verifying that your service point is CORS Enabled. In order to focus solely on CORS functionality, I would remove the MySQL code temporarily.
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(cors());
app.get('/', function(req, res){
var root = {};
root.status = 'success';
root.method = 'index';
var json = JSON.stringify(root);
res.send(json);
});
app.post('/cors', function(req, res) {
var root = {};
root.status = 'success';
root.method = 'cors';
var json = JSON.stringify(root);
res.send(json);
})
// Start the server
app.listen(3300, () => {
console.log('Listening on port 3300');
});
您有一个服务器正在监听3300端口,请在终端上运行以下PREFLIGHT命令.
One you have server listening on port 3300, run the following PREFLIGHT command at the terminal.
curl -v \
-H "Origin: https://example.com" \
-H "Access-Control-Request-Headers: X-Custom-Header" \
-H "Acess-Control-Request-Method: POST" \
-X OPTIONS \
http://localhost:3300
如果预检请求成功,则响应应包括Access-Control-Allow-Origin,Access-Control-Allow-Methods和Access-Control-Allow-Header
If the preflight request is successful, the response should include Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers
现在运行POST方法.
Now run the POST method.
curl -v \
-H "Origin: https://example.com" \
-H "X-Custom-Header: value" \
-X POST \
http://localhost:3300/cors
如果发布请求成功,则响应应包括 访问控制允许来源
If the post request is successful, the response should include Access-Control-Allow-Origin
如果一切正常,则您的服务器正常.然后,您需要在iOS应用中尝试发布方法.
If everything looks good, your server is okay. You then need to try the post method from your iOS app.
注意.我也会对在本地主机上使用cors感到怀疑.我会将127.0.0.1映射到一个域,然后让应用程序改用该域.如果您使用的是Linux或Mac,则可以修改/etc/hosts.对于Windows,它是c:\ windows \ system32 \ drivers \ etc \ hosts
NOTE. I would also be suspicious of using cors on localhost. I would map 127.0.0.1 to a domain and then have the app use that domain instead. If you are on Linux or Mac, you modify /etc/hosts. For Windows it's c:\windows\system32\drivers\etc\hosts