react怎么将数据存到mysql中,在React.js Web应用程序中将数据发送到数据库

I'm creating a web application and I'm curious how to send data to MySQL database in it. I have a function that is invoked when user presses button, I want this function somehow to send data to the MySQL server. Does anyone know how to approach this problem? I tried npm MySQL module but it seems the connection doesn't work as it is client side. Is there any other way of doing it? I need an idea to get me started.

Regards

解决方案

You will need a server that handles requests from your React app and updates the database accordingly. One way would be to use NodeJS, Express and node-mysql as a server:

var mysql = require('mysql');

var express = require('express');

var app = express();

// Set up connection to database.

var connection = mysql.createConnection({

host: 'localhost',

user: 'me',

password: 'secret',

database: 'my_db',

});

// Connect to database.

// connection.connect();

// Listen to POST requests to /users.

app.post('/users', function(req, res) {

// Get sent data.

var user = req.body;

// Do a MySQL query.

var query = connection.query('INSERT INTO users SET ?', user, function(err, result) {

// Neat!

});

res.end('Success');

});

app.listen(3000, function() {

console.log('Example app listening on port 3000!');

});

Then you can use fetch within a React component to do a POST request to the server, somewhat like this:

class Example extends React.Component {

constructor() {

super();

this.state = { user: {} };

this.onSubmit = this.handleSubmit.bind(this);

}

handleSubmit(e) {

e.preventDefault();

var self = this;

// On submit of the form, send a POST request with the data to the server.

fetch('/users', {

method: 'POST',

data: {

name: self.refs.name,

job: self.refs.job

}

})

.then(function(response) {

return response.json()

}).then(function(body) {

console.log(body);

});

}

render() {

return (

);

}

}

Keep in mind that this is only one of infinite ways to achieve this.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值