ReactJS connection with database











up vote
0
down vote

favorite












I want to get the data from front end react js form and insert in to mysql database using backend express. Can you tell me the flow from front end to backend with simple one field form using react js and then insert into database.










share|improve this question






















  • I have make till now signup form in reactjs.
    – Himanshu Pandey
    Apr 18 '17 at 6:25






  • 1




    people will be hesitant to help until you show you've made an effort. Post some links to docs you've read. Show your attempt at coding this, then post your code and ask for help
    – singmotor
    May 15 at 17:27










  • That's make sense .. absolutely correct
    – Himanshu Pandey
    May 15 at 17:39










  • I don't really understand what is it that you don't know. The way your question is phrased sounds like you don't know anything about web development, which might lead to a different answer to what you expect. Please specify what is it that you don't know, so that we can answer according
    – Christopher Francisco
    May 31 at 15:23















up vote
0
down vote

favorite












I want to get the data from front end react js form and insert in to mysql database using backend express. Can you tell me the flow from front end to backend with simple one field form using react js and then insert into database.










share|improve this question






















  • I have make till now signup form in reactjs.
    – Himanshu Pandey
    Apr 18 '17 at 6:25






  • 1




    people will be hesitant to help until you show you've made an effort. Post some links to docs you've read. Show your attempt at coding this, then post your code and ask for help
    – singmotor
    May 15 at 17:27










  • That's make sense .. absolutely correct
    – Himanshu Pandey
    May 15 at 17:39










  • I don't really understand what is it that you don't know. The way your question is phrased sounds like you don't know anything about web development, which might lead to a different answer to what you expect. Please specify what is it that you don't know, so that we can answer according
    – Christopher Francisco
    May 31 at 15:23













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I want to get the data from front end react js form and insert in to mysql database using backend express. Can you tell me the flow from front end to backend with simple one field form using react js and then insert into database.










share|improve this question













I want to get the data from front end react js form and insert in to mysql database using backend express. Can you tell me the flow from front end to backend with simple one field form using react js and then insert into database.







mysql reactjs express frontend backend






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Apr 18 '17 at 6:16









Himanshu Pandey

1111113




1111113












  • I have make till now signup form in reactjs.
    – Himanshu Pandey
    Apr 18 '17 at 6:25






  • 1




    people will be hesitant to help until you show you've made an effort. Post some links to docs you've read. Show your attempt at coding this, then post your code and ask for help
    – singmotor
    May 15 at 17:27










  • That's make sense .. absolutely correct
    – Himanshu Pandey
    May 15 at 17:39










  • I don't really understand what is it that you don't know. The way your question is phrased sounds like you don't know anything about web development, which might lead to a different answer to what you expect. Please specify what is it that you don't know, so that we can answer according
    – Christopher Francisco
    May 31 at 15:23


















  • I have make till now signup form in reactjs.
    – Himanshu Pandey
    Apr 18 '17 at 6:25






  • 1




    people will be hesitant to help until you show you've made an effort. Post some links to docs you've read. Show your attempt at coding this, then post your code and ask for help
    – singmotor
    May 15 at 17:27










  • That's make sense .. absolutely correct
    – Himanshu Pandey
    May 15 at 17:39










  • I don't really understand what is it that you don't know. The way your question is phrased sounds like you don't know anything about web development, which might lead to a different answer to what you expect. Please specify what is it that you don't know, so that we can answer according
    – Christopher Francisco
    May 31 at 15:23
















I have make till now signup form in reactjs.
– Himanshu Pandey
Apr 18 '17 at 6:25




I have make till now signup form in reactjs.
– Himanshu Pandey
Apr 18 '17 at 6:25




1




1




people will be hesitant to help until you show you've made an effort. Post some links to docs you've read. Show your attempt at coding this, then post your code and ask for help
– singmotor
May 15 at 17:27




people will be hesitant to help until you show you've made an effort. Post some links to docs you've read. Show your attempt at coding this, then post your code and ask for help
– singmotor
May 15 at 17:27












That's make sense .. absolutely correct
– Himanshu Pandey
May 15 at 17:39




That's make sense .. absolutely correct
– Himanshu Pandey
May 15 at 17:39












I don't really understand what is it that you don't know. The way your question is phrased sounds like you don't know anything about web development, which might lead to a different answer to what you expect. Please specify what is it that you don't know, so that we can answer according
– Christopher Francisco
May 31 at 15:23




I don't really understand what is it that you don't know. The way your question is phrased sounds like you don't know anything about web development, which might lead to a different answer to what you expect. Please specify what is it that you don't know, so that we can answer according
– Christopher Francisco
May 31 at 15:23












2 Answers
2






active

oldest

votes

















up vote
0
down vote
















**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';
class 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.handlePasswordChange = this.handlePasswordChange.bind(this);
this.state = {
email:'',
password:'',
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,
password: this.state.password
})
.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})
}
handlePasswordChange(e){
this.setState({password: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 className="form-signin" history={this.props.history}>
<h2 className="form-signin-heading"> Please sign in </h2>
<label className="sr-only"> Email address
</label>
}
<input type="email" onChange={this.handleEmailChange} id="inputEmail" className="form-control" placeholder="Email address" required />
<label htmlFor="inputPassword" className="sr-only"> Password</label>

<input type="password" onChange={this.handlePasswordChange} id="inputPassword" className="form-control" placeholder="Password" required />

<button className="btn btn-lg btn-primary btn-block" onClick={this.signIn} type="button">Sign in</button>
</form>
);
}
}
}
export default withRouter(Login);



**On Express**


var express = require('express');
var bodyParser = require('body-parser');
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({
host : 'localhost',
user : 'root',
password : '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.password);

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;








share|improve this answer

















  • 1




    Please add an explaination to your code. Furthermore your code snippet does not work, so either make it work or remove the functionality to use the code as a code snippet.
    – L. Guthardt
    Jul 10 at 6:59


















up vote
-1
down vote













Here's a simple example that establishes a connection to mysql.



var mysql = require('mysql')
var connection = mysql.createConnection({
host : 'localhost',
user : 'dbuser',
password : '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






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f43464908%2freactjs-connection-with-database%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote
















    **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';
    class 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.handlePasswordChange = this.handlePasswordChange.bind(this);
    this.state = {
    email:'',
    password:'',
    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,
    password: this.state.password
    })
    .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})
    }
    handlePasswordChange(e){
    this.setState({password: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 className="form-signin" history={this.props.history}>
    <h2 className="form-signin-heading"> Please sign in </h2>
    <label className="sr-only"> Email address
    </label>
    }
    <input type="email" onChange={this.handleEmailChange} id="inputEmail" className="form-control" placeholder="Email address" required />
    <label htmlFor="inputPassword" className="sr-only"> Password</label>

    <input type="password" onChange={this.handlePasswordChange} id="inputPassword" className="form-control" placeholder="Password" required />

    <button className="btn btn-lg btn-primary btn-block" onClick={this.signIn} type="button">Sign in</button>
    </form>
    );
    }
    }
    }
    export default withRouter(Login);



    **On Express**


    var express = require('express');
    var bodyParser = require('body-parser');
    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({
    host : 'localhost',
    user : 'root',
    password : '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.password);

    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;








    share|improve this answer

















    • 1




      Please add an explaination to your code. Furthermore your code snippet does not work, so either make it work or remove the functionality to use the code as a code snippet.
      – L. Guthardt
      Jul 10 at 6:59















    up vote
    0
    down vote
















    **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';
    class 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.handlePasswordChange = this.handlePasswordChange.bind(this);
    this.state = {
    email:'',
    password:'',
    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,
    password: this.state.password
    })
    .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})
    }
    handlePasswordChange(e){
    this.setState({password: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 className="form-signin" history={this.props.history}>
    <h2 className="form-signin-heading"> Please sign in </h2>
    <label className="sr-only"> Email address
    </label>
    }
    <input type="email" onChange={this.handleEmailChange} id="inputEmail" className="form-control" placeholder="Email address" required />
    <label htmlFor="inputPassword" className="sr-only"> Password</label>

    <input type="password" onChange={this.handlePasswordChange} id="inputPassword" className="form-control" placeholder="Password" required />

    <button className="btn btn-lg btn-primary btn-block" onClick={this.signIn} type="button">Sign in</button>
    </form>
    );
    }
    }
    }
    export default withRouter(Login);



    **On Express**


    var express = require('express');
    var bodyParser = require('body-parser');
    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({
    host : 'localhost',
    user : 'root',
    password : '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.password);

    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;








    share|improve this answer

















    • 1




      Please add an explaination to your code. Furthermore your code snippet does not work, so either make it work or remove the functionality to use the code as a code snippet.
      – L. Guthardt
      Jul 10 at 6:59













    up vote
    0
    down vote










    up vote
    0
    down vote












    **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';
    class 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.handlePasswordChange = this.handlePasswordChange.bind(this);
    this.state = {
    email:'',
    password:'',
    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,
    password: this.state.password
    })
    .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})
    }
    handlePasswordChange(e){
    this.setState({password: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 className="form-signin" history={this.props.history}>
    <h2 className="form-signin-heading"> Please sign in </h2>
    <label className="sr-only"> Email address
    </label>
    }
    <input type="email" onChange={this.handleEmailChange} id="inputEmail" className="form-control" placeholder="Email address" required />
    <label htmlFor="inputPassword" className="sr-only"> Password</label>

    <input type="password" onChange={this.handlePasswordChange} id="inputPassword" className="form-control" placeholder="Password" required />

    <button className="btn btn-lg btn-primary btn-block" onClick={this.signIn} type="button">Sign in</button>
    </form>
    );
    }
    }
    }
    export default withRouter(Login);



    **On Express**


    var express = require('express');
    var bodyParser = require('body-parser');
    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({
    host : 'localhost',
    user : 'root',
    password : '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.password);

    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;








    share|improve this answer















    **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';
    class 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.handlePasswordChange = this.handlePasswordChange.bind(this);
    this.state = {
    email:'',
    password:'',
    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,
    password: this.state.password
    })
    .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})
    }
    handlePasswordChange(e){
    this.setState({password: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 className="form-signin" history={this.props.history}>
    <h2 className="form-signin-heading"> Please sign in </h2>
    <label className="sr-only"> Email address
    </label>
    }
    <input type="email" onChange={this.handleEmailChange} id="inputEmail" className="form-control" placeholder="Email address" required />
    <label htmlFor="inputPassword" className="sr-only"> Password</label>

    <input type="password" onChange={this.handlePasswordChange} id="inputPassword" className="form-control" placeholder="Password" required />

    <button className="btn btn-lg btn-primary btn-block" onClick={this.signIn} type="button">Sign in</button>
    </form>
    );
    }
    }
    }
    export default withRouter(Login);



    **On Express**


    var express = require('express');
    var bodyParser = require('body-parser');
    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({
    host : 'localhost',
    user : 'root',
    password : '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.password);

    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;








    **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';
    class 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.handlePasswordChange = this.handlePasswordChange.bind(this);
    this.state = {
    email:'',
    password:'',
    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,
    password: this.state.password
    })
    .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})
    }
    handlePasswordChange(e){
    this.setState({password: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 className="form-signin" history={this.props.history}>
    <h2 className="form-signin-heading"> Please sign in </h2>
    <label className="sr-only"> Email address
    </label>
    }
    <input type="email" onChange={this.handleEmailChange} id="inputEmail" className="form-control" placeholder="Email address" required />
    <label htmlFor="inputPassword" className="sr-only"> Password</label>

    <input type="password" onChange={this.handlePasswordChange} id="inputPassword" className="form-control" placeholder="Password" required />

    <button className="btn btn-lg btn-primary btn-block" onClick={this.signIn} type="button">Sign in</button>
    </form>
    );
    }
    }
    }
    export default withRouter(Login);



    **On Express**


    var express = require('express');
    var bodyParser = require('body-parser');
    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({
    host : 'localhost',
    user : 'root',
    password : '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.password);

    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;





    **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';
    class 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.handlePasswordChange = this.handlePasswordChange.bind(this);
    this.state = {
    email:'',
    password:'',
    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,
    password: this.state.password
    })
    .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})
    }
    handlePasswordChange(e){
    this.setState({password: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 className="form-signin" history={this.props.history}>
    <h2 className="form-signin-heading"> Please sign in </h2>
    <label className="sr-only"> Email address
    </label>
    }
    <input type="email" onChange={this.handleEmailChange} id="inputEmail" className="form-control" placeholder="Email address" required />
    <label htmlFor="inputPassword" className="sr-only"> Password</label>

    <input type="password" onChange={this.handlePasswordChange} id="inputPassword" className="form-control" placeholder="Password" required />

    <button className="btn btn-lg btn-primary btn-block" onClick={this.signIn} type="button">Sign in</button>
    </form>
    );
    }
    }
    }
    export default withRouter(Login);



    **On Express**


    var express = require('express');
    var bodyParser = require('body-parser');
    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({
    host : 'localhost',
    user : 'root',
    password : '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.password);

    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;






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Jul 10 at 6:30









    Nilesh Badgi

    62




    62








    • 1




      Please add an explaination to your code. Furthermore your code snippet does not work, so either make it work or remove the functionality to use the code as a code snippet.
      – L. Guthardt
      Jul 10 at 6:59














    • 1




      Please add an explaination to your code. Furthermore your code snippet does not work, so either make it work or remove the functionality to use the code as a code snippet.
      – L. Guthardt
      Jul 10 at 6:59








    1




    1




    Please add an explaination to your code. Furthermore your code snippet does not work, so either make it work or remove the functionality to use the code as a code snippet.
    – L. Guthardt
    Jul 10 at 6:59




    Please add an explaination to your code. Furthermore your code snippet does not work, so either make it work or remove the functionality to use the code as a code snippet.
    – L. Guthardt
    Jul 10 at 6:59












    up vote
    -1
    down vote













    Here's a simple example that establishes a connection to mysql.



    var mysql = require('mysql')
    var connection = mysql.createConnection({
    host : 'localhost',
    user : 'dbuser',
    password : '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






    share|improve this answer



























      up vote
      -1
      down vote













      Here's a simple example that establishes a connection to mysql.



      var mysql = require('mysql')
      var connection = mysql.createConnection({
      host : 'localhost',
      user : 'dbuser',
      password : '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






      share|improve this answer

























        up vote
        -1
        down vote










        up vote
        -1
        down vote









        Here's a simple example that establishes a connection to mysql.



        var mysql = require('mysql')
        var connection = mysql.createConnection({
        host : 'localhost',
        user : 'dbuser',
        password : '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






        share|improve this answer














        Here's a simple example that establishes a connection to mysql.



        var mysql = require('mysql')
        var connection = mysql.createConnection({
        host : 'localhost',
        user : 'dbuser',
        password : '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







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited May 31 at 15:49

























        answered May 31 at 15:19









        DJ2

        12310




        12310






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f43464908%2freactjs-connection-with-database%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Bressuire

            Vorschmack

            Quarantine