Reputation: 1449
I have concern right now regarding sending the request body from my react native to the back end express JS. Once the button press or click, the logs from my server shows undefined. All get methods are working, except the post method. I read a lot of documents regarding on that.
Imported module:
const express = require('express');
var cors = require('cors')
const bodyParser = require('body-parser');
const mysql = require('mysql');
const app = express();
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
var cors = require('cors');
app.use(cors());
Post Method:
app.post('/api/new_readings/', function (req, res) {
connection.getConnection(function (err, connection) {
console.log(req.body.name);
});
});
Submit Handler:
fetch('http://myippppp:3000/api/new_readings/', {
method: 'POST',
headers:
{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: {
"name": "x",
"email": "a",
"password": "1234"
}
})
.then(response => response.json())
.then(serverResponse => console.warn(serverResponse))
Error:
Hope someone help on this.
Upvotes: 0
Views: 736
Reputation: 13588
The correct syntax is
Client side
fetch('http://myippppp:3000/api/new_readings/', {
method: 'POST',
headers:
{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"name": "x",
"email": "a",
"password": "1234"
}) // need to use JSON.stringify
})
.then(response => response.json())
.then(serverResponse => console.warn(serverResponse))
Server Side
app.post('/api/new_readings/', function (req, res) {
console.log(req.body.name);
return res.json({ ok: true });
});
Upvotes: 1