Wednesday, 15 May 2019

Sending Data from React to MySQL

I am creating a publishing application that needs to use communication between React and MySQL database to send information back and forth. Using Express as my JS server. The server code looks as follows:

const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const cors = require('cors');
const connection = mysql.createConnection({
   host     : 'localhost',
   user     : 'root',
   password : '',
   database : 'ArticleDatabase',
   port: 3300,
   socketPath: '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock'
  });

// Initialize the app
const app = express();
app.use(cors());

appl.post('/articletest', function(req, res) {
   var art = req.body;
   var query = connection.query("INSERT INTO articles SET ?", art,    
      function(err, res) {
         })
   })

// https://expressjs.com/en/guide/routing.html
app.get('/comments', function (req, res) {
// connection.connect();

connection.query('SELECT * FROM articles', function (error, results,  
  fields) {
    if (error) throw error;
    else {
         return res.json({
            data: results
         })
    };
});

//    connection.end();
});

// Start the server
app.listen(3300, () => {
   console.log('Listening on port 3300');
 });

And my React class looks as follows:

class Profile extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        title: '',
        author: '',
        text: ''
    }
}

handleSubmit() {
    // On submit of the form, send a POST request with the data to the  
    //  server.
    fetch('http://localhost:3300/articletest', {
        body: JSON.stringify(this.state),
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            'content-type': 'application/json'
        },
        method: 'POST',
        mode: 'cors',
        redirect: 'follow',
        referrer: 'no-referrer',
    })
        .then(function (response) {
            console.log(response);
            if (response.status === 200) {
                alert('Saved');
            } else {
                alert('Issues saving');
            }
        });
}

render() {
   return (
    <div>
      <form onSubmit={() => this.handleSubmit()}>
        <input type = "text" placeholder="title" onChange={e =>  
           this.setState({ title: e.target.value} )} />
        <input type="text" placeholder="author" onChange={e => 
          this.setState({ author: e.target.value} )}  />
        <textarea type="text" placeholder="text" onChange={e => 
          this.setState({ text: e.target.value}  )} />
        <input type="Submit" />
      </form>
   </div>
   );
  }
}

So fairly standard stuff that I found in online tutorials. I can search my database and display fetched info no problem, but not the other way around. When I try to take input from the <form> tag nothing is inserted into my database but instead I get this error:

[Error] Fetch API cannot load    
http://localhost:3000/static/js/0.chunk.js due to access control 
checks.
Error: The error you provided does not contain a stack trace.
Unhandled Promise Rejection: TypeError: cancelled

I understand that this has something to do with access control but since I am already using cors and can successfully retrieve data from the database, I am not sure what I am doing wrong. Any suggestions will be greatly appreciated. Thank you in advance.



from Sending Data from React to MySQL

No comments:

Post a Comment