React Native post to Node.js/Express - node.js

I am triying to make a post query from my React Native (expo) app to Node.js server (express). And the post is doing nothing. Even, console.log doesnot work. Please, need your help with this
React Native App code:
const options = {
method: 'POST',
timeout: 20000,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8'
},
body: JSON.stringify({
a: 10,
b: 20
})
};
fetch(url, options)
.then(response => {
console.log(response.status);
})
.catch(error => console.error('timeout exceeded'));
console.log('3232');
And node.js code:
var express = require('express');
/// create express app
var app = express();
app.use(express.json());
app.post('/g_data/auth', function(req, res){
console.log('LOGGED')
res.send('Hello World!')
});
React Native console return : "3232"
node.js console return nothing
No "new incoming connection detected from ...", "LOGGED", as expected.
Please help, what I am doing wrong?

maybe u need to install and import body-parser on your node js
var express = require('express');
var bodyParser = require('body-parser'); // ++
/// create express app
var app = express();
app.use(express.json());
app.use(bodyParser.urlencoded({extended: false})); // ++
app.post('/g_data/auth', function(req, res){
console.log('LOGGED')
res.send('Hello World!')
});

Ok! the final solution is in wrong Headers. For some reasons, React Native app send Headers:
'Content-Type': 'application/json;charset=UTF-8'
But node.js server receives:
'Content-Type': 'text/plain;charset=UTF-8'
So, first, I have installed cors to server, npm i cors -save and for some reason left Body Parser, and a little bit modernize headers. Here is a final code:
React Native App:
let formdata = '["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]';
///console.log(formdata);
const url = 'http://192.168.88.15:7935/g_data/auth';
const options = {
method: 'POST',
timeout: 20000,
mode:'cors',
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
body: formdata
};
fetch(url, options)
.then((response) => response.json())
/// make design
setLoading(false);
/// next code
console.log('next!');
The server code is:
var express = require('express');
var cors = require('cors')
var bodyParser = require('body-parser');
/// create express app
var app = express();
/// use cors
app.use(cors())
/// use body req parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/g_data/auth', function(req, res){
console.log(req.body)
res.send({Message: 'Hello World!'})
});
app.listen(7935);
console.log('listen port 7935');

Related

request.body is empty on posting data from react to node using axios

I am trying to post the data from react (front end) to nodejs server using axios api call, the url is hit and executes properly, but the the sent data is empty
Node code*
const express = require("express");
const bodyParser = require('body-parser');
const cors = require("cors");
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
let corsOptions = {
origin: "*",
optionsSuccessStatus: 200,
};
app.use(cors(corsOptions));
app.post("/signin",function(request,response,next){
console.log(request);
console.log(request.body);
response.json({});
})
app.listen(4000, "localhost", function () {
console.log("App is listening at port 4000");
});
React Method
onSignin=function(event){
let data = new FormData();
data.append("signinEmail",this.state.signinEmail);
axios({
method:"post",
url:"http://localhost:4000/signin",
data:data,
headers:{
'Content-Type':'multipart/form-data'
}
}).then((res)=>{
console.log(res);
})
}
any help is appreciated.
If you don't need to upload a file in /signin API, you can use 'Content-Type':'application/json' and send a JSON object to the server.
onSignin=function(event){
// data send to server
let data = {
signinEmail : this.state.signinEmail
};
axios({
method:"post",
url:"http://localhost:4000/signin",
data:data,
headers:{
'Content-Type':'application/json'
}
}).then((res)=>{
console.log(res);
})
}

Unirest post request body

I want to be able to send data from one server to another, started on the same device (to start with). I have this:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const urlEncodedParser = bodyParser.urlencoded({extended: false});
app.post('/test', urlEncodedParser, (request, response) =>
{
console.log(request.body);
});
app.listen(9999);
console.log('Server started on port 9999');
const unirest = require('unirest');
unirest.post('http://127.0.0.1:9999/test').headers({'Accept': 'application/json', 'Content-Type': 'application/json'}).send({"test1": 123321, "test2": "321123"})
.then((response) =>
{
console.log(response.body);
});
It looks logical, but console.log(request.body); gives empty object {} yet in the post requests I do send some data using .send. How to get access to that data in the request?
You are sending data with Content-Type: 'application/json', so on the server you need to connect middleware not for urlencoded, but for json. In addition, you do not need to separately connect the body-parser since it is included in express and you can connect the necessary middleware like this:
Server:
const express = require('express');
const app = express();
app.post('/test', express.json(), (request, response) => {
console.log(request.body);
response.end('OK');
});
app.listen(9999, () => console.log('Server started on port 9999'));
Client:
const unirest = require('unirest');
unirest
.post('http://127.0.0.1:9999/test')
.headers({ Accept: 'application/json', 'Content-Type': 'application/json' })
.send({ test1: 123321, test2: '321123' })
.then((response) => {
console.log(response.body);
});

send json with request to express in node

I have 2 node js apps one sending a post request as follows:
request.post({
url: url,
headers: {"content-type": "application/json"},
json: {a:1,b:2}
},
function (error, response, body) {
//..
}
);
and the other is trying to handle it with express and body-parser:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/verify', (req, res,cb = (err, res) => {}) => {
var data = req.body; //returns empty json!
// ..
}
the problem is that at the receiving end I can't retrieve the json data I'm looking for. Does any body know what I'm missing?
Adding this to your server side code should work:
app.use(bodyParser.json())

Express JS is receiving an empty req.body from ReactJS

I am currently having a problem with React and Express JS form submit function. It seems like my nodeJS running on port 5000 is receiving an empty object from my ReactJS running on port 8080 using fetch method.
React : Contact.js
handleSubmit(e)
{
e.preventDefault();
var data = {
name: this.state.name,
contact: this.state.contact,
email: this.state.email,
message: this.state.message,
}
var url = 'http://localhost:5000/api/insertUsers';
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
mode: 'no-cors',
body: JSON.stringify(data),
})
.catch((error) => {
console.log(error);
});
}
NodeJS : server.js
const express = require('express');
const { Client } = require('pg');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/api/insertUsers', function(req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
});
app.listen(5000, () => {
console.log('listening on port 5000');
});
Change the order of bodyparser middleware like this.
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
You are sending a request with the content-type of 'application/json' but express is expecting a content-type of 'text/json'. Usually, when req.body is empty content-type is the first suspect you should be looking at.
I am ashamed that I struggled with this for hours. I still haven't gotten it to work with file uploads.
But I did get it to work with a normal form by encoding JSON and sending that along with axios, instead of fetch
My js code
var data = {
id: this.state.id,
}
console.log('data',data)
var bodyFormData = new FormData();
bodyFormData.set('id', this.state.id);
var url = ' http://localhost:3000/get-image-by-id';
console.log("bodyFormData: ", bodyFormData);
axios({
method: 'post',
url: url,
data: data,
// headers: {'Content-Type': 'multipart/form-data' }
headers: {'Content-Type': 'application/x-www-form-urlencoded' }
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
Form Code
<form method="POST" onSubmit={this.handleSubmit} >
<label>
Transaction ID
<input
type="text"
name="id"
value={this.state.id}
onChange={this.handleInputChange}
/>
</label>
<button type="submit">Submit</button>
</form>
```
EDIT
fetch(url, {
method: 'POST',
body: JSON.stringify(data),
mode: 'no-cors'
}).then((result)=>{
console.log("output" + result.json());
})
.catch((error) => {
console.log(error);
});
EDIT 2
for backend, install cors and add the following lines before route.
var cors = require('cors')
app.use(cors())
EDIT 3
perform npm install morgan then copy these lines inside the code
var morgan = require('morgan');
app.use(morgan('dev'));
I didn't look at your code close enough. My bad
app.post('/api/insertUsers', function(req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
});
Should be
app.post('/api/insertUsers', function(req, res) {
res.json(req.body)
});
try using axios instead of fetch
I rewrote ur code like this and it works perfectly
server
const express = require('express');
const { Client } = require('pg');
const bodyParser = require('body-parser');
const app = express();
const cors = require("cors");
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/api/insertUsers', function(req, res) {
// console.log(req);
console.log(req.body);
res.send(req.body);
});
app.listen(3001, () => {
console.log('listening on port 3001');
});
react (ensure you have axios installed)
handleSubmit(e){
e.preventDefault();
var data = {
name: "zadiki",
contact: "0702002109",
email: "zadiki",
message: "test",
}
console.log("wow");
var url = ' http://localhost:3001/api/insertUsers';
axios.post(url,data)
.then(response=>console.log(response))
.catch(e=>console.log(e))
}
Hello I ended up getting mine working after I ran into the same problem.
I noticed your react code has "mode: 'no-cors'," that was causing problems with mine so I removed it.
-------- Below is my handle submit code for React ------------
const handleSubmit = (event) => {
event.preventDefault();
const url = "http://localhost:3001/register"
const options = {
method: "POST",
body: JSON.stringify(formData),
headers: {
"Content-Type": "application/json"
}
}
fetch(url, options)
.then(res => res.json())
.then(res => console.log(res))
}
I used express.json instead of bodyParser. You also had a typo in your express code, it should say res.send instead of res.end
--------- Below is my Node Express Code -----------
const express = require('express');
const app = express();
const cors = require('cors');
const multer = require('multer');
// Middlewares
app.use(cors({ origin: 'http://localhost:3000', }))
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(multer().array());
app.post('/register',(req, res) => {
console.log(req.body)
res.status(200)
.json({status:"Success", data:{body: req.body })
});
app.listen(3001, () => console.log(`Running on 3001`))
I was able to send form data using postman and react using the code above. Feel free to change it to accommodate your needs.

cant get req object in post fetch

Code of the node.js program:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser')
var app = express();
var cors = require('cors');
app.use(express.static(path.join(__dirname,'../client/' ,'build')));
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(cors());
app.post('/',(req,res)=>{
console.log(req.body); //always empty
})
I think the node.js program is right but every time front-end application hits the url req.body is always empty and I don't know why.
My front-end application is built with React.js and below is the code where I call the fetch().
fetch('/', {
method: 'POST',
body: JSON.stringify({
task: details
}),
headers: {
"Content-Type": "application/json"
}
})
Try changing couple things:
In your frontend:
fetch('/', {
method: 'POST',
body: { task: details },
headers: { "Content-Type": "application/json" }
})
In your server side:
app.post('/',(req,res)=>{
console.log(JSON.stringify(req.body)); //always empty
})
This should works.

Resources