Hi guys, I'm beginner for React JS. Therefore, I want to learning how can used together React JS, Node JS and MySQL. So, Please give me some advises and example. I try do solve this problem. please help me guys.
i want to define connection in different file called server.js and get and post method in defferent file called routes.js......
is there any solution for that????
Pankaj Patel
Blog, Tech, Photography etc.
React.js is front end when will call the endpoints to load the data from back end.
Node.js + MySQL are for backend.
First you can pick any one from express, hapi, koa, restify etc. and then build the API to do the CRUD operations on data.
Then you can choose to either have REST API or GraphQL. You can start with REST as you will not need to do too much configuration.
Considering express, following example will give a list of posts from the posts table:
const express = require('express'); const bodyParser = require('body-parser'); const mysql = require('mysql'); // github.com/mysqljs/mysql const connection = mysql.createConnection({ host : 'localhost', user : 'me', password : 'secret', database : 'my_db' }); // Initialize the app const app = express(); // expressjs.com/en/guide/routing.html app.get('/posts', function (req, res) { connection.connect(); connection.query('SELECT * FROM posts LIMIT 0, 10', function (error, results, fields) { if (error) throw error; res.send(results) }); connection.end(); }); // Start the server app.listen(3000, () => { console.log('Go to localhost/posts to see posts'); });And on react:
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; class Posts extends Component { constructor(props) { super(props); this.state = { posts: [] }; fetch('localhost/posts') .then(resposnse => response.json()) .then(posts => (this.setState({posts})) } render() { return (<div> Hello World <ul> {this.state.posts.map(post => <li> <h2>{post.title}</h2> <p>{post.body}</p> </li>} </ul> </div>); } } ReactDOM.render( <Posts />, mountNode );Code above is a rough example, rest you can figure out by
documentation,trial-and-errorandstack-overflow