当前位置: 首页 > Web前端 > HTML

React+Node+Express搭建前端demo

时间:2023-04-02 23:30:01 HTML

1.简单demo:之前用原生JS写了一个计算器,这里想写在react里面,用数据库记录每一个计算公式和结果,可以发请求获取后台部分:数据库之后建立后,通过Node.jsexpress框架编写操作数据库前端页面的接口:通过react的router控制路由写入,然后通过axios向后台发送请求得到最终结果http://counter.jianjiacheng.com文档比较简单易学,这里简单说明一下2.1新建express项目webstorm可以直接点击newporject选择expressApp2.2项目结构和路由挂载├──app.js#的主入口application├──bin#启动脚本├──node_modules#依赖模块├──package.json#node模块的配置文件├──public#css、js等静态资源存放目录├──routes#路由规则存放目录└──views#模板文件存放目录2.3路由路由写在routesvarexpress=require('express');varrouter=express.Router();router.get('/list',function(req,res,next){//pool.query是数据库的连接池。下面会说pool.query('SELECT*FROMcounter;',function(err,rows,fields){if(err)throwerr;console.log(rows)res.json(rows)})});router.post('/add',function(req,res,next){console.log(req.body)//varmysqltl='INSERTINTOcounter(id,counter,time)VALUES(\''+req.body.counter+'\','+'now()'+');'varmysqltl=`INSERTINTOcounter(counter,time)VALUES('${req.body.counter}',now());`console.log(mysqltl)pool.query(mysqltl,function(err,rows,fields)){if(err)throwerr;console.log(rows)res.json(rows)})});2.4允许跨域请求设置添加app.all('*',function(req,res,next){res.header('Access-Control-Allow-Origin','*');res.header('Access-Control-Allow-Headers','Content-Type');res.header('Access-Control-Allow-Methods','*');res.header('Content-Type','application/json;charset=utf-8');next();});2.5express连接数据库2.5.1。直接通过createConnection创建连接。该方法需要释放连接。不推荐使用varmysql=require('mysql');varconnection=mysql.createConnection({host:'localhost',user:'root',password:'******',database:'mytest'//你的数据库名})connection.connect()2.5.2.通过连接池进行连接,可以实现高并发,不需要释放连接varmysql=require('mysql');varpool=mysql.createPool({connectionLimit:100,//处理主机的最大连接数:'localhost',用户:'root',密码:'****',数据库:'mytest'});2.6运行程序3.数据库建立,请求应该没什么好说的,根据自己的情况建表就大功告成了。数据库建立后,通过express中的路由页面接受前台的请求,通过SQL语句操作数据库。这里,我使用axios发送前台请求。如果没有,可以使用cnpminstallaxios--saveaxios({method:'post',headers:{'Content-type':'application/json'},url:'http://localhost:3000/counter/add',data:{counter:input+"="+value,}}).then(function(response){console.log(response);}).catch(function(error){console.日志(错误);});4.React前端页面构建4.1App.js:通过react的router控制界面路由,如果不按照cnpminstallreact-router-dom--saveimportReact,{Component}from'react';importCounterView来自'./Pages/CounterView/index';从'./Page导入CounterHistorys/CounterHistory/index';从'./Pages/Login/index'导入登录;从'react-router-dom'导入{HashRouter,Router,Route,Switch,Link,BrowserRouter};导入'./App.css';classAppextendsComponent{render(){return(

  • 首页
  • 计数器
  • 历史记录
  • );}}exportdefaultApp;4.2写法是通过写一个方方便导入数据的button组件,通过预定义数组动态生成界面4.3效果图和核心代码'../../Utils/Enum';从'./index.less'导入样式;从'axios'导入axios;classCounterViewextendsComponent{constructor(props){super(props);这。state={inputValue:"",};}getButtonArr=(value=[])=>{varButtonArr=[];value.forEach((outval)=>{outval.forEach((inval)=>{ButtonArr.push({value:inval})})})returnButtonArr;}count=()=>{varinput=this.state.inputValuetry{varvalue=eval(input).toFixed(2);const_this=this;axios({method:'post',headers:{'Content-type':'application/json'},url:'http://localhost:3000/counter/add',data:{counter:input+"="+value,}}).then(function(response){console.log(response);}).catch(function(error){console.日志(错误);});返回值;}catch(err){alert("表达式错误")}}getValue=(e)=>{varnewInputValue=this.state.inputValue;varid=e.target.innerText;if(id!=="clear"&&id!=="back"&&id!=="equal"&&id!=="sign"){newInputValue=this.state.inputValue+id;}if(id==="="){varvalue=this.count();新输入值=值;}if(id==="clear"){newInputValue="";}if(id==="back"){newInputValue=this.state.inputValue.substring(0,this.state.inputValue.length-1);}if(id==="√"){varvalue=this.count();如果(值){newInputValue=Math.sqrt(值);}else{newInputValue="";}}this.setState({inputValue:newInputValue,})}changeValue=(e)=>{varnewInputValue=e.target.value;console.log(newInputValue)this.setState({inputValue:newInputValue,})}render(){varButtonArr=this.getButtonArr(BUTTON_VALUE)return(this.changeValue(e)}/>this.getValue(e)}>{/*事件委托加载mybutton上无效*/}
    )}}exportdefaultCounterView;importReact,{Component}from'react';classMyButtonextendsComponent{render(){return(
    {this.props.data.map(数据=><按钮value={data.value}key={data.value}style={{width:this.props.width,height:this.props.height}}>{data.value})}
    );}}exportdefaultMyButton;importReact,{Component}from'react';importaxiosfrom'axios';importmomentfrom'moment';import'./index.less';classCounterHistoryextendsComponent{constructor(props){超级(道具);this.state={数据:[],};}componentDidMount(){this.getdata();}getdata=()=>{const_this=this;axios.get('http://localhost:3000/counter').then(function(response){console.log(response)_this.setState({数据:响应.数据,});}).catch(function(error){console.log(error);})}del=(e)=>{const_this=this;constid=e.target.id;axios({method:'post',headers:{'Content-type':'application/json'},url:'http://localhost:3000/counter/del',data:{id:id,}}).then(function(response){_this.getdata();}).catch(function(error){console.log(error);});}changeValue=(e)=>{}render(){vardata=this.state.data;console.log(data)return(
    index历史计算<spanclassName="time">计算时间运算
    {data.map((data,index)=>{index+1}{data.counter}{moment(data.time).format('YYYY-MM-DDHH:mm:ss')}this.del(event)}>删除
    )}
    )}}导出默认CounterHistory;源码界面https://github.com/jianjiache...后台https://github.com/jianjiache...