cant get req object in post fetch - node.js

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.

Related

req.body is blank in POST requests (Express node)

Server Code:
const express = require('express')
const app = express() app.use(express.static('public')) app.use(express.json({limit :'100mb'}));
app.post('/post', (req, res) => { console.log('post called');
console.log(req.body); ////Printed here
})
app.listen(3000)
Client code:
const data ={agent: 41}
const options = {
method: 'POST',
mode: 'no-cors',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
};
fetch('http://localhost:3000/post', options);
output in server terminal
can anyone please tell me what am i doing wrong, how can i get the value?
Expected Output :
{agent: 41}
On you client code, why are you using mode: 'no-cors' option?
Removing it will fix your problem.
const data = { agent: 41 }
const options = { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) };
fetch('http://localhost:3000/post', options);
Here you can find an explaination on what is happening.
If you were using mode: 'no-cors' to handle a cors error, this is not the way to go. You should use the cors middleware in you Express based application.
const express = require('express')
const cors = require('cors')
const app = express()
app.use(cors()) // use it as first middleware

React Native post to Node.js/Express

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');

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);
})
}

Can't find the request body on my POST request

I am using Node and Express to handle my back-end requests. I make a call from the front end:
const newData = {id: sub, first_name: given_name, last_name: family_name, email: email}
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newData)
}
fetch(`/add`, requestOptions)
.then(res => res.json())
.then(data => console.log(data))
.catch(console.log('error2'));
which get picked up by my "/add" end-point. For now I just want to console.log the request body so my end point is:
router.post('/add', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
console.log(req.body, 'hit')
})
However the server console log comes out as {} 'hit'. When I use the network tab I can see that the request has a payload containing id, first_name, last_name, and email.
Could anyone tell me what I am missing to get my data into my server.
Also my server is set up with body-parser like this:
const bodyParser = require('body-parser');
const app = express();
app.use(
bodyParser.urlencoded({
extended: false,
})
);
As you are sending an application/json content type, you should use bodyParser.json() instead of bodyParser.urlencoded({ extended: false }).
Ex:
const bodyParser = require('body-parser');
const app = express();
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.

Resources