将数据从 React 发送到 MySQL

Posted

技术标签:

【中文标题】将数据从 React 发送到 MySQL【英文标题】:Sending Data from React to MySQL 【发布时间】:2019-09-20 13:55:33 【问题描述】:

我正在创建一个发布应用程序,它需要使用 React 和 mysql 数据库之间的通信来来回发送信息。使用 Express 作为我的 JS 服务器。服务器代码如下:

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 类如下所示:

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>
   );
  

我在在线教程中找到的相当标准的东西。我可以搜索我的数据库并显示获取的信息没有问题,但反过来不行。当我尝试从 &lt;form&gt; 标记中获取输入时,我的数据库中没有插入任何内容,但我得到了这个错误:

[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 并且可以成功地从数据库中检索数据,所以我不确定我做错了什么。任何建议将不胜感激。提前谢谢你。

【问题讨论】:

您是否在提交表单时检查过您是否正在获取字段值?在状态?还要确保您在路由器回调函数中获得准确的数据。我在我的应用程序中使用 postgresSQL 数据库和反应组件测试了相同的代码。它就像魅力一样。 亚历山大,你介意发布赏金吗?谢谢。 【参考方案1】:

您需要首先验证您的服务点是否已启用 CORS,从而找出问题所在。为了只关注 CORS 功能,我将暂时删除 MySQL 代码。

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 命令。

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-Headers

现在运行 POST 方法。

curl -v \
-H "Origin: https://example.com" \
-H "X-Custom-Header: value" \
-X POST \
http://localhost:3300/cors

如果发布请求成功,响应应包括 访问控制允许来源

如果一切正常,您的服务器就可以了。然后,您需要从您的 ios 应用程序中尝试 post 方法。

注意。我也会怀疑在本地主机上使用 cors。我会将 127.0.0.1 映射到域,然后让应用程序使用该域。如果您使用的是 Linux 或 Mac,则修改 /etc/hosts。对于 Windows,它是 c:\windows\system32\drivers\etc\hosts

【讨论】:

是的,一切都如你所说,我得到了正确的响应,但是当我尝试从 React 应用程序发布时,它仍然给我同样的错误。 好的,我必须启动 React 代码才能解决该部分的问题。【参考方案2】:

尝试将发出请求的服务器明确列入白名单:

const whitelist = ['http://localhost:3000']; // React app

const corsInstance = cors(
  origin: (origin, callback) => 
    if (!origin || whitelist.indexOf(origin) !== -1) 
      callback(null, true);
     else 
      callback(new Error('Not allowed by CORS'));
    
  
);

application.use(corsInstance);

https://expressjs.com/en/resources/middleware/cors.html#configuring-cors-w-dynamic-origin

【讨论】:

将上面的代码插入到我的 server.js 文件中,不幸的是还是同样的错误... @AlexanderNenartovich 它是否记录Not allowed by CORS 错误?如果是这样,请尝试记录 origin 以查看被拒绝的内容。 它记录了我上面显示的完全相同的错误 - Fetch API can not load localhost:3000... 由于访问控制检查。它没有具体说明 CORS。【参考方案3】:

您需要在handleSubmit 方法的末尾添加event.preventDefault()(查看此示例https://stackblitz.com/edit/react-forms)。

您必须这样做是为了防止提交时的表单默认行为:它尝试将数据同步发送到它加载的 url(因为它没有 action 属性)。

【讨论】:

不起作用,抱歉。错误,无法评估未定义的属性(未定义事件)。 它适用于 StackBlitz 并且应该适用于您的应用程序。很可能您没有将event 参数传递给handleSubmit 方法。 我确实传递了事件参数。现在没有错误,但没有任何反应。没有任何东西被插入到数据库中,也没有任何东西被发送到服务器。不知道发生了什么。 你是对的,将事件参数传递给 handleSubmit 处理了那个未定义的错误,但是现在当我点击提交按钮时,什么也没有发生。没有错误,也没有数据被发送或插入到任何我能看到的地方。 您为我解决这个问题节省了一周的时间。这是基于您的回答的更详细的解决方案,以防万一有人需要这个:***.com/a/60911038/3909488【参考方案4】:

对于那些可能遇到类似问题的人,我可以通过完全转储快递服务器来解决它。我只是使用 Apache 服务器上的 .php 文件将数据插入数据库。希望它可以帮助某人。

【讨论】:

以上是关于将数据从 React 发送到 MySQL的主要内容,如果未能解决你的问题,请参考以下文章