Sending Data from React to MySQL
You'll need to isolate the problem by first verifying that your service point is CORS Enabled. In order to focus solely on CORS functionality, I would remove the MySQL code temporarily.
const express = require('express');const bodyParser = require('body-parser');const cors = require('cors');const app = express();app.use(cors());app.get('/', function(req, res){ var root = {}; root.status = 'success'; root.method = 'index'; var json = JSON.stringify(root); res.send(json);});app.post('/cors', function(req, res) { var root = {}; root.status = 'success'; root.method = 'cors'; var json = JSON.stringify(root); res.send(json);})// Start the serverapp.listen(3300, () => { console.log('Listening on port 3300'); });
One you have server listening on port 3300, run the following PREFLIGHT command at the terminal.
curl -v \-H "Origin: https://example.com" \-H "Access-Control-Request-Headers: X-Custom-Header" \-H "Acess-Control-Request-Method: POST" \-X OPTIONS \http://localhost:3300
If the preflight request is successful, the response should include Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers
Now run the POST method.
curl -v \-H "Origin: https://example.com" \-H "X-Custom-Header: value" \-X POST \http://localhost:3300/cors
If the post request is successful, the response should includeAccess-Control-Allow-Origin
If everything looks good, your server is okay. You then need to try the post method from your iOS app.
NOTE. I would also be suspicious of using cors on localhost. I would map 127.0.0.1 to a domain and then have the app use that domain instead. If you are on Linux or Mac, you modify /etc/hosts. For Windows it's c:\windows\system32\drivers\etc\hosts
Try explicitly whitelisting the server that is making the request:
const whitelist = ['http://localhost:3000']; // React appconst corsInstance = cors({ origin: (origin, callback) => { if (!origin || whitelist.indexOf(origin) !== -1) { callback(null, true); } else { callback(new Error('Not allowed by CORS')); } }});application.use(corsInstance);
https://expressjs.com/en/resources/middleware/cors.html#configuring-cors-w-dynamic-origin
You need to add event.preventDefault()
at the end of your handleSubmit
method (check this example https://stackblitz.com/edit/react-forms).
You have to do it for the reason for preventing form default behavior on submit: it tries to synchronously send data to the url it loaded from (since there is no action
attribute on it).