Ad

Using MySQL With React : Questions And CORS Problem

- 1 answer

I'm trying to access my mySQL data in my react app. For this, i use 2 files :

For react :

var request = require("request");
var option = {
    url : 'http://localhost:3001/test',
    headers : {
        'Access-Control-Allow-Origin':'*'
    },
    json : true,
    body : {
        option : "myoption"
    },
    mode: 'cors',
    method :"GET"
};

request(option, function (error, response, body) {
    console.log('error:', error);
    console.log('statusCode:', response && response.statusCode);
    console.log('body:', body);
});
ReactDOM.render(<App />, document.getElementById('root'));
serviceWorker.unregister();

For SQL :

function create_connect(){
    var connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'root',
        password : '',
        database : 'site'
    });
    connection.connect();
    console.log("connected");
    return connection;
}

app.get('/test', function (req, res) {
var connection = create_connect();
console.log(req.body);

connection.query('SELECT * FROM test', function (error, results, fields) {
  console.log(error);
    console.log(results);
    console.log(fields);
  res.send(results)
});

connection.end();
});
app.listen(3001, () => {
 console.log('Launched');
});

However, i get "Error: Invalid value for opts.mode" when i put the "mode:'cors'" or "mode:'no-cors'" and "Access to fetch at 'http://localhost:3001/test' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."

when i don't. How do i fix this ?

Also, I used the right syntax the get the body.option right ? And is the res.send(result) caught by console.log("body":body)?

Ad

Answer

On your node.js application you need to enable CORS. If you are using express.js you could do that by using cors lirbary

npm install cors

And then enable all CORS requests:

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

In production you will want to restrict CORS request only from your domain.

More information about CORS you can found on this link.

Ad
source: stackoverflow.com
Ad