我想从前端反应 js 表单获取数据,并使用后端快递插入到 mysql 数据库。你能告诉我从前端到后端的流程简单的一个字段形式使用反应 js,然后插入数据库。
让我们举一个简单的库应用程序的例子,它的表(books
)带有字段book_name
和autr
。
让我们先看看后端代码(在节点 Js 中)
const express = require('express');
const bodyPr = require('body-pr');
var connection = require('express-myconnection');
var mysql = require('mysql');
const app = express();
app.use(bodyPr.json());
app.use(
connection(mysql,{
st: 'localst', //'localst',
user: 'userEHX',
pword : 'hMmx56FN4GHpMXOl',
port : 3306, //port mysql
database:'sampledb'
},'l')); //or single
app.post('/add_book',(req,res)=>{
let {book_name,autr,} = req.body;
if(!book_name) return res.status(400).json('Book Name cant be blank');
if(!autr) return res.status(400).json('Autr cant be blank');
var data={book_name:book_name,
autr:autr};
var query = connection.query("INSERT INTO books set ? ",data,
function(err, rows)
{
if (err){
//If error
res.status(400).json('Sorry!!Unable To Add'));
console.log("Error inserting : %s ",err );
}
else
//If success
res.status(200).json('Book Added Successfully!!')
});
});
app.listen(3000, ()=> {
console.log(`app is running on port 3000`);
});
现在让我们看看 React Js 上的前端代码:
import React from 'react';
export default cl AddBook extends React.Component {
constructor(){
super();
this.state = {
bookname:'',
autr:'',
};
}
updateInfo = (event) =>{
let fieldName = event.target.name;
let fieldValue = event.target.value;
if(fieldName === 'bookname') {
this.setState({bookname: fieldValue});
}
else if(fieldName === 'autr'){
this.setState({autr:fieldValue});
}
};
addBook=(e)=>{
let {bookname,autr}=this.state;
fetch('localst:3000/add_book', {
metd: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
bookname:bookname,
autr:autr,
})
}).then(response=>response.json()).then(data=>{
window.alert(data)
//Do anything else like Toast etc.
})
}
render(){
return(
<div clName="add_book">
<div>
<label>Book Name</label>
<input onChange={this.updateInfo} name="bookname" value{this.state.bookname}/>
</div>
<div>
<label >Autr</label>
<input onChange={this.updateInfo} name="autr" value={this.state.autr}/>
</div>
<on onClick={this.addBook}>Add</on>
</div>
)
}
}
下面是一个简单的例子,建立一个连接到 mysql。
var mysql = require('mysql')
var connection = mysql.createConnection({
st : 'localst',
user : 'dbuser',
pword : 's3kreee7',
database : 'my_db'
});
connection.connect()
connection.query('SELECT 1 + 1 AS solution', function (err, rows, fields) {
if (err) throw err
console.log('The solution is: ', rows[0].solution)
})
connection.end()
Helpful guide to integrate popular Node.js modules for DBs
**On REACT**
import React, { Component } from 'react';
import axios from "axios";
import {
BrowserRouter as Router,
Route,
Link,
Redirect,
withRouter
} from "react-router-dom";
import createHistory from "history/createBrowserHistory"
//import isLoggedIn from '../../helpers/is_logged_in';
cl Login extends Component {
constructor(props) {
const history = createHistory();
super(props);
// this.islogin = this.islogin.bind(this);
this.signIn = this.signIn.bind(this);
this.handleEmailChange = this.handleEmailChange.bind(this);
this.handlePwordChange = this.handlePwordChange.bind(this);
this.state = {
email:'',
pword:'',
redirectToReferrer: false
};
}
signIn(){
const history = createHistory()
const location = history.location;
console.log(location);
// alert(this.state.email);
axios.post('http://192.168.1.35:3012/users', {
email: this.state.email,
pword: this.state.pword
})
.then(function (response) {
// console.log(response.data[0].id);
// console.log(response.data.email);
var das = localStorage.setItem('sessionid', response.data[0].id);
var das = localStorage.setItem('myData', response.data[0].name);
var da = localStorage.getItem('myData');
var myid = sessionStorage.setItem('myid', response.data[0].id);
//alert(da);
//history.go('/dash');
})
.catch(function (error) {
console.log(error);
});
this.setState({ redirectToReferrer: true });
}
handleEmailChange(e){
this.setState({email:e.target.value})
}
handlePwordChange(e){
this.setState({pword:e.target.value})
}
render() {
console.log('11111');
const myid = sessionStorage.getItem('myid');
const { from } = this.props.location.state || { from: { pathname: "/dash" } };
const { redirectToReferrer } = this.state;
if (redirectToReferrer || myid !=null) {
console.log('22222');
return <Redirect to={from} />;
}
else{
return (
<form clName="form-signin" history={this.props.history}>
<h2 clName="form-signin-heading"> Please sign in </h2>
<label clName="sr-only"> Email address
</label>
}
<input type="email" onChange={this.handleEmailChange} id="inputEmail" clName="form-control" placelder="Email address" required />
<label htmlFor="inputPword" clName="sr-only"> Pword</label>
<input type="pword" onChange={this.handlePwordChange} id="inputPword" clName="form-control" placelder="Pword" required />
<on clName="btn btn-lg btn-primary btn-block" onClick={this.signIn} type="on">Sign in</on>
</form>
);
}
}
}
export default withRouter(Login);
**On Express**
var express = require('express');
var bodyPr = require('body-pr');
var app = express();
var fs = require('fs');
var formidable = require('formidable');
var busboy = require('connect-busboy');
var cors = require('cors')
var router = express.Router();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var mysql = require('mysql')
var connection = mysql.createConnection({
st : 'localst',
user : 'root',
pword : 'test',
database : 'example'
});
connection.connect(function(err) {
if (err) throw err
// console.log('You are now connected...')
})
/* POST users listing. */
router.post('/', function(req, res, next) {
console.log(req.body.email);
user_sql = "INSERT INTO table_name VALUES (req.body.name, req.body.pword);
console.log(user_sql)
connection.query(user_sql, function (err, rows, fields) {
if (err) throw err
console.log(rows)
res.end(JSON.stringify(rows));
// res.json(rows);
});
});
module.exports = router;
本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处
评论列表(45条)