将数据从 React 发送到 MySQL

本文介绍了将数据从 React 发送到 MySQL的处理方法,对大家解决问题具有一定的参考价值

问题描述

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

const express = require('express');const bodyParser = require('body-parser');const mysql = 要求('mysql');const cors = 要求('cors');常量连接 = mysql.createConnection({主机:'本地主机',用户:'root',密码 : '',数据库:'文章数据库',端口:3300,socketPath: '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock'});//初始化应用常量应用程序 = 快递();app.use(cors());appl.post('/articletest', function(req, res) {var art = req.body;var query = connection.query("INSERT INTO article SET ?", art,功能(错误,水库){})})//https://expressjs.com/en/guide/routing.htmlapp.get('/comments', function (req, res) {//连接.connect();connection.query('SELECT * FROM items', function (error, results,字段){if (error) 抛出错误;别的 {返回 res.json({数据:结果})};});//连接.end();});//启动服务器app.listen(3300, () => {console.log('监听 3300 端口');});

我的 React 类如下所示:

class Profile 扩展 React.Component {构造函数(道具){超级(道具);这个.state = {标题: '',作者: '',文本: ''}}处理提交(){//在提交表单时,发送一个带有数据的 POST 请求到// 服务器.fetch('http://localhost:3300/articletest', {正文:JSON.stringify(this.state),缓存:'无缓存',凭据:'同源',标题:{内容类型":应用程序/json"},方法:'POST',模式:'cors',重定向:'关注',推荐人:'无推荐人',}).then(函数(响应){控制台日志(响应);if (response.status === 200) {警报(已保存");} 别的 {alert('问题保存');}});}使成为() {返回 (
<表单提交={() =>this.handleSubmit()}><输入类型=文本"占位符=标题"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} )}/><输入类型="提交"/></表格></div>);}}

我在在线教程中找到的相当标准的东西.我可以搜索我的数据库并显示获取的信息没问题,但反过来不行.当我尝试从 <form> 标记获取输入时,没有任何内容插入到我的数据库中,而是出现此错误:

[错误] Fetch API 无法加载http://localhost:3000/static/js/0.chunk.js 由于访问控制检查.错误:您提供的错误不包含堆栈跟踪.未处理的承诺拒绝:TypeError:取消

我知道这与访问控制有关,但由于我已经在使用 cors 并且可以成功地从数据库中检索数据,所以我不确定我做错了什么.任何建议将不胜感激.提前谢谢你.

解决方案

您需要通过首先验证您的服务点是否已启用 CORS 来隔离问题.为了只关注 CORS 功能,我将暂时删除 MySQL 代码.

const express = require('express');const bodyParser = require('body-parser');const cors = 要求('cors');常量应用程序 = 快递();app.use(cors());app.get('/', function(req, res){变种根 = {};root.status = '成功';root.method = '索引';var json = JSON.stringify(root);res.send(json);});app.post('/cors', function(req, res) {变种根 = {};root.status = '成功';root.method = 'cors';var json = JSON.stringify(root);res.send(json);})//启动服务器app.listen(3300, () => {console.log('监听 3300 端口');});

如果您有服务器在端口 3300 上侦听,请在终端上运行以下 PREFLIGHT 命令.

curl -v -H "来源:https://example.com" -H访问控制请求标头:X-自定义标头"-H访问控制请求方法:POST"-X 选项http://localhost:3300

如果预检请求成功,响应应包括 Access-Control-Allow-Origin、Access-Control-Allow-Methods 和 Access-Control-Allow-Headers

现在运行 POST 方法.

curl -v -H "来源:https://example.com" -H "X-Custom-Header: 值" -X 发布http://localhost:3300/cors

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

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

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

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

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

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

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.

解决方案

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

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

If the preflight request is successful, the response should include Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers

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

If everything looks good, your server is okay. You then need to try the post method from your iOS app.

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:windowssystem32driversetchosts

这篇关于将数据从 React 发送到 MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2

admin_action_{$_REQUEST[‘action’]}

do_action( "admin_action_{$_REQUEST[‘action’]}" )动作钩子::在发送“Action”请求变量时激发。Action Hook: Fires when an ‘action’ request variable is sent.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$_REQUEST['action']引用从GET或POST请求派生的操作。源码(Source)更新版本源码位置使用被使用2.6.0 wp-admin/admin.php:...

日期:2020-09-02 17:44:16 浏览:1127

admin_footer-{$GLOBALS[‘hook_suffix’]}

do_action( "admin_footer-{$GLOBALS[‘hook_suffix’]}", string $hook_suffix )操作挂钩:在默认页脚脚本之后打印脚本或数据。Action Hook: Print scripts or data after the default footer scripts.目录锚点:#说明#参数#源码说明(Description)钩子名的动态部分,$GLOBALS['hook_suffix']引用当前页的全局钩子后缀。参数(Parameters)参数类...

日期:2020-09-02 17:44:20 浏览:1033

customize_save_{$this->id_data[‘base’]}

do_action( "customize_save_{$this-&gt;id_data[‘base’]}", WP_Customize_Setting $this )动作钩子::在调用WP_Customize_Setting::save()方法时激发。Action Hook: Fires when the WP_Customize_Setting::save() method is called.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_data...

日期:2020-08-15 15:47:24 浏览:775

customize_value_{$this->id_data[‘base’]}

apply_filters( "customize_value_{$this-&gt;id_data[‘base’]}", mixed $default )过滤器::过滤未作为主题模式或选项处理的自定义设置值。Filter Hook: Filter a Customize setting value not handled as a theme_mod or option.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_date['base'],指的是设置...

日期:2020-08-15 15:47:24 浏览:866

get_comment_author_url

过滤钩子:过滤评论作者的URL。Filter Hook: Filters the comment author’s URL.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/comment-template.php:32610...

日期:2020-08-10 23:06:14 浏览:903

network_admin_edit_{$_GET[‘action’]}

do_action( "network_admin_edit_{$_GET[‘action’]}" )操作挂钩:启动请求的处理程序操作。Action Hook: Fires the requested handler action.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$u GET['action']引用请求的操作的名称。源码(Source)更新版本源码位置使用被使用3.1.0 wp-admin/network/edit.php:3600...

日期:2020-08-02 09:56:09 浏览:848

network_sites_updated_message_{$_GET[‘updated’]}

apply_filters( "network_sites_updated_message_{$_GET[‘updated’]}", string $msg )筛选器挂钩:在网络管理中筛选特定的非默认站点更新消息。Filter Hook: Filters a specific, non-default site-updated message in the Network admin.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分$_GET['updated']引用了非默认的...

日期:2020-08-02 09:56:03 浏览:834

pre_wp_is_site_initialized

过滤器::过滤在访问数据库之前是否初始化站点的检查。Filter Hook: Filters the check for whether a site is initialized before the database is accessed.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/ms-site.php:93910...

日期:2020-07-29 10:15:38 浏览:809

WordPress 的SEO 教学:如何在网站中加入关键字(Meta Keywords)与Meta 描述(Meta Description)?

你想在WordPress 中添加关键字和meta 描述吗?关键字和meta 描述使你能够提高网站的SEO。在本文中,我们将向你展示如何在WordPress 中正确添加关键字和meta 描述。为什么要在WordPress 中添加关键字和Meta 描述?关键字和说明让搜寻引擎更了解您的帖子和页面的内容。关键词是人们寻找您发布的内容时,可能会搜索的重要词语或片语。而Meta Description则是对你的页面和文章的简要描述。如果你想要了解更多关于中继标签的资讯,可以参考Google的说明。Meta 关键字和描...

日期:2020-10-03 21:18:25 浏览:1621

谷歌的SEO是什么

SEO (Search Engine Optimization)中文是搜寻引擎最佳化,意思近于「关键字自然排序」、「网站排名优化」。简言之,SEO是以搜索引擎(如Google、Bing)为曝光媒体的行销手法。例如搜寻「wordpress教学」,会看到本站的「WordPress教学:12个课程…」排行Google第一:关键字:wordpress教学、wordpress课程…若搜寻「网站架设」,则会看到另一个网页排名第1:关键字:网站架设、架站…以上两个网页,每月从搜寻引擎导入自然流量,达2万4千:每月「有机搜...

日期:2020-10-30 17:23:57 浏览:1264