send json with request to express in node - node.js

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())

Related

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

How can I receive post from node js sent with form data from Angular frontend

I posted data on angular front end as formData like this.
postButton(name: string): Observable<any> {
const formData = new FormData();
formData.append('name', name);
return this.http.post(environment.apiUrl + '/url, formData);
}
And I receive data on Node.js front end like this.
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/api/url', (req, res, next) => {
console.log(req.body)
res.status(200).json({
'message': 'OK',
});
});
But I get {},empty value.
what is wrong in my code?
Regards.
According to my knowledge, if you are sending some file then using FormData is useful. In other scenario's like this in which you are just sending plain text. You can just send a normal json object and it will work. You can try this.
postButton(name: string): Observable<any> {
return this.http.post(environment.apiUrl + '/url, { name });
}
In case you really want to use FormData then you need to install a npm package as:
npm install multer
And change your app.js to:
var express = require('express');
var app = express();
var multer = require('multer');
var upload = multer();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(upload.array());
app.use(express.static('public'));
app.post('/api/url', function (req, res) {
console.log(req.body);
});
module.exports = app;
Now, what multer does is, it supports multi-part form submission. And FromData uses that. To get the data from request body you need to install and configure multer.
Hope this works for you.
Delete the Content-Type header:
postButton(name: string): Observable<any> {
const formData = new FormData();
formData.append('name', name);
const httpOptions = {
headers: new HttpHeaders().delete('Content-Type')
};
return this.http.post(environment.apiUrl + '/url, formData, httpOptions);
}
When the XHR API send method sends a FormData Object, it automatically sets the content type header with the appropriate boundary. When the Angular http service overrides the default content type, the server will get a content type header without the proper boundary.

Can Not POST NodeJS Express

I was trying to make an axios post request to an express server and I receive that Error: Request failed with status code 404 at createError. Postman says Can Not POST. I don't know what could be wrong, i'm new in all this, so all the help it's good, thanks.
Axios and Express server are from 2 different link. They are google cloud function.
Thanks for the help
Axios Post Request :
exports.notification = (req, res) => {
var axios = require('axios');
var https = require('https');
var bodyParser = require('body-parser');
var config = {
headers: {
'Content-Type' : 'application/x-www-form-urlencoded',
'Content-Type' : 'text/html',
'Content-Type' : 'application/json' }
};
var info = {
ids:[req.body.id,req.body.id1],
type: req.body.type,
event: req.body.action,
subscription_id: req.body.subid,
secret_field_1:null,
secret_field_2:null,
updated_attributes:{
field_name:[req.body.oname,req.body.nname]}
};
var myJSON = JSON.stringify(info);
return axios.post('https://us-central1-copper-mock.cloudfunctions.net/api/notification-example', myJSON)
.then((result) => {
console.log("DONE",result);
})
.catch((err) => {
console.log("ERROR",err);
console.log("Error response:");
console.log(err.response.data);
console.log(err.response.status);
console.log(err.response.headers);
})
};
Express Server
const express = require ('express');
const https = require ('https');
const bodyParser = require ('body-parser');
const app = express();
const port = 8080;
// ROUTES
var router = express.Router(); // get an instance of router
router.use(function(req, res, next) { // route middleware that will happen on every request
console.log(req.method, req.url); // log each request to the console
next(); // continue doing what we were doing and go to the route
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/',require ('./Routers/API/home'));
app.use('/leads',require ('./Routers/API/leads'));
app.use('/people',require ('./Routers/API/people'));
app.use('/companies',require ('./Routers/API/companies'));
app.use('/opportunities',require ('./Routers/API/opportunities'));
app.use('/projects',require ('./Routers/API/projects'));
app.use('/tasks',require ('./Routers/API/tasks'));
app.use('/activities',require ('./Routers/API/activities'));
app.use('/notification-example',require ('./Routers/API/notification_example'));
app.use('/', router); // apply the routes to our application
// START THE SERVER
// ==============================================
app.listen(port);
console.log('Listening ' + port);
module.exports={
app
};
Notification Route
const express = require('express');
const router = express.Router();
//const notification_example = require('../../Notification');
router.get('/', function(req, res) {
console.log('DATA',JSON.parse(res.data));
console.log('BODY',JSON.parse(res.body));
});
module.exports = router;

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.

req.body.variablename is undefined in express with body-parser middleware

I am using express 4.14.1 version in my Nodejs application. I am also using body parser middleware for parsing form data but when I write console.log(req.body.variablename) I get undefined on the console.
my code is as follows
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser'); //parses information from POST
const request = require('request');
const mongodb = require('../model/mongodb.js');
const smtpTransport = require('../model/mailer.js');
const Agent = require('../model/agentmodel.js');
const config = require('../config.js');
const intent = require('../intents.js');
const ejs = require('ejs');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// use res.render to load up an ejs view file
router.get('/chat', function(req,res){
// res.sendFile(path.join(__dirname + '/html/' + '/index.html'));
res.render('pages/index', { heading: config.property.userheading});
});
// use res.render to load up an ejs view file
router.get('/', function(req,res){
// res.sendFile(path.join(__dirname + '/html/' + '/index.html'));
res.render('pages/helpdesk');
});
router.post('/createTicket', function(req,res){
console.log("create ticket is called from email support");
console.log(req.body);
console.log("and the details as follows ==>");
console.log("username is ==> "+req.body.userName);
console.log("message is ==>"+req.body.message);
var json = {
name : req.body.userName,
email : req.body.userEmail,
subject: 'Demo Subject',
message: req.body.message,
topicId : req.body.topicId,
};
var options = {
url: 'http://domainname/iprhelpdesk/upload/api/http.php/tickets.json',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key' : 'API-key'
},
json:json
};
request(options, function(err, res, body) {
if (res && (res.statusCode === 200 || res.statusCode === 201)) {
console.log("response is ==>");
console.log(res);
}
else {
console.log("error is "+err+ " = and reponse code is ="+res.statusCode );
}
});
res.render('pages/message');
});
following is the output of the console
create ticket is called from email support {
'{"topicId":{"Id":12,"name":"Basic IPR Query"},"message":"i want to
know about ipr","userName":"Pawan
Patil","country":"IN","userEmail":"pawanpatil.rocks#gmail.com","contact":"09665714555"}':
'' } and the details as follows ==> username is ==> undefined message
is ==>undefined POST /createTicket 200 21.161 ms - 104 error is null =
and reponse code is =400
and this is what chrome is sending as a form data
{"topicId":{"Id":12,"name":"Basic IPR Query"},"message":"i want to
know about ipr","userName":"Jon
Snow","country":"IN","userEmail":"test#test.com","contact":"0123456789"}:
Request header is
Content-Type:application/x-www-form-urlencoded
everything seems to be perfect but still, I am getting
undefined
when I write console.log("username is ==> "+req.body.userName); in my code.
please help me out
Move those:
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
Before this:
app.use(app.router)
So your bodyParser need to be initialized before the router. I also have read that using this:
app.use(require('connect').bodyParser());
Insted of:
app.use(express.bodyParser());
May also fix the problem with undefined req.body
And one more thing to try is:
app.use(bodyParser.urlencoded({ extended: false}));
Set extended to be false instead of true
I have solved the problem from changing
Content-Type:application/x-www-form-urlencoded
header to the
Content-Type: application/json

Resources