Nodejs not receiving POST body - angularjs

I'm sending a POST in angularjs like so:
$http.post("/mypath", { data: "foobar" })
And in nodejs (expressjs) I'm trying to pick it up like so:
app.post "/mypath", (req, res) ->
console.log "req.body: ", req.body
res.end()
I've tried various different incarnations (body: "foobar", etc), but I keep getting req.body: undefined
Is there a simple way to read the payload in node/express?

To get data from a POST in Node, you need to use a body Parser. eg:
var bodyParser = require('body-parser');
//use bodyParser() to let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

Related

Using bodyParser for solution to Payload Too Large

Novice here. I am trying to send a photo within a rich-text editor to the API but receive the 413-payload too large error. I've read that the solution to this is to use a body-parser but once I try that it messes up all my routing. Since I'm a novice and used YouTube tutorials to put the routing together I'm not exactly sure how to fix it with the body-parser.
I'm proxying API Requests using "proxy": "http://localhost:8800/api/ in the package.json and using express' app.use with axios to post/get data from mysql database. For example:
const app = express()
app.use(express.json())
app.use("/api/posts", postRoutes)
const router = express.Router()
router.get("/", getPosts)
export const getPosts = (req, res)=>{
const q = req.query.cat ? "SELECT * FROM posts WHERE cat=?" : "SELECT * FROM posts"
db.query(q, [req.query.cat], (err, data) =>{
if(err) return res.status(500).send(err);
return res.status(200).json(data);
}
)
}
I tried using body-parser
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
but I get the error
Proxy error: Could not proxy request /posts from localhost:3001 to http://localhost:8800/api (ECONNRESET).
Any help or direction will be must appreciated.

Receiving "Cannot GET /" error when trying to connect using Node.js/Express

Recently I started trying to get into Node.js/React and am using this tutorial https://auth0.com/blog/build-a-chat-app-with-react/.
However, even though I have followed the steps, I seem to be encountering an error. My page is displayed as "Cannot GET /" after hitting yarn start. I've found answers here NodeJS w/Express Error: Cannot GET /
and here "Cannot GET /" with Connect on Node.js
Neither of these made sense to me though, as my code seems to differ from theirs slightly. I understand that the page doesnt know where to look for my GET request, and therefore what information to pull, but im not sure how to fix it.
The code in question, GET request at the end. Thanks.
// server.js
const express = require('express');
const path = require('path');
const bodyParser = require("body-parser");
const app = express();
const Pusher = require('pusher');
//initialize Pusher with your appId, key and secret
const pusher = new Pusher({
appId: 'APP_ID',
key: 'APP_KEY',
secret: 'SECRET',
cluster: 'YOUR CLUSTER',
encrypted: true
});
// Body parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// API route which the chat messages will be sent to
app.post('/message/send', (req, res) => {
// 'private' is prefixed to indicate that this is a private channel
pusher.trigger( 'private-reactchat', 'messages', {
message: req.body.message,
username: req.body.username
});
res.sendStatus(200);
});
// API route used by Pusher as a way of authenticating users
app.post('/pusher/auth', (req, res) => {
const socketId = req.body.socket_id;
const channel = req.body.channel_name;
const auth = pusher.authenticate(socketId, channel);
res.send(auth);
});
// Set port to be used by Node.js
app.set('port', (process.env.PORT || 5000));
app.listen(app.get('port'), function(req, res) {
console.log('Node app is running on port', app.get('port'));
});
I assume that you are sending get request to localhost:5000 which isn't defined in your server so it can't send response back, because you are using react you want to send request on port on which react is running(3000 by default) so try accessing using localhost:3000 and it should work.
You need to have the route available in the code. Try reading up on Express Basic Routing
Try the below and take it from there. I'm assuming that you're running on port 5000, if not, point to whatever port is set in process.env.PORT
app.get('/', function (req, res) {
res.send('hello world');
})

req.body in nodejs is coming empty:{}?

This is my angular http request which makes a delete request when deleteEmployee function is called:
This function is called on click of event:
$scope.deleteEmployee=function(index){
$http({
method:'DELETE',
url:'/delete',
data:{
"ndx":"abc"
}
}).then((response)=>{
console.log(response);
})
}
And this is my server.js file
var http=require('http');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/',express.static(__dirname));
app.delete('/delete',function(req,res){
console.log(req.body);
})
app.listen(8888,()=>{
console.log('Server Started');
})
On console.log(req.body) it show empty i.e. {}.
From https://www.rfc-editor.org/rfc/rfc7231#section-4.3.5:
A payload within a DELETE request message has no defined semantics; sending a payload body on a DELETE request might cause some existing implementations to reject the request.
Basically, DELETE requests must not have a body.
Try changing syntax :
$http.delete('/delete',{"ndx":"abc"});

req.body empty Node.js

this is my angular controller code where im passing certificationid and userid to delete certification details of a user.
$scope.deleteCertification = function(CertificationId){
var userName = $scope.userId;
var certificationId = CertificationId;
var deleteCertificationInfo = {'userName': userName, 'certificationId':certificationId};
console.log('deleteCertificationInfo*******');
console.log(deleteCertificationInfo);
userProfileService.deleteUserCertificationInfo(deleteCertificationInfo).then (function(data){
console.log($scope.Certification);
console.log('Certification Deleted');
})
}
userProfileData.deleteUserCertificationInfo = function (deleteCertificationInfo) {
var deferred = $q.defer();
$http.delete('/api/profileUpdate/deleteUserCertification', deleteCertificationInfo, {
}).success(function(res){
var deletedUserCertificationResult = res;
deferred.resolve(deletedUserCertificationResult);
$log.debug('response from certification API:['+JSON.stringify(deletedUserCertificationResult)+']');
}).error(function(err){
deferred.reject(err);
});
return deferred.promise;
};
that is written in userProfileService to call the delete API.
but in my node controller function req.body is empty. not sure where it is going. im consoling the data in front end before sending it to service . it's displayed then. but why the req.body is getting empty?
Even though you haven't posted the Express portion of your app, the best guess here is that you're not using body-parser. body-parser is an Express middleware that is required when using req.body, without adding it to your Express app, you won't be able to parse any incoming JSON or url-encoded request bodies.
const express = require('express');
const bodyParser = require('body-parser');
const port = process.env.PORT || 3000;
let app = express();
app.use(bodyParser.json()); // this will parse Content-Type: application/json
app.use(bodyParser.urlencoded({ extended: true })); // this will parse Content-Type: application/x-www-form-urlencoded
// Your routes go here
app.listen(port);
try with the follwing code, its worked for me , you shoud have this code in your node service js file
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));

In Express.js with body-parser the value of request.body is undefined

I'm having a problem I cannot diagnose.
On a server, I have a simple URL handler using Express.js:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var multer = require('multer');
app.configure(function() {
app.use(app.router);
app.use(bodyParser.json()); // see: http://expressjs.com/api.html#req.body
app.use(bodyParser.urlencoded({
extended: true
}));
});
app.post('/submit', function (req, res) {
console.log(req.body);
});
On client side, there's a form which is handled with Angular controller:
$scope.submit = function () {
// $http.post('/submit', $scope.data); // POST request to send data to the server
$http({
method: 'POST',
url: '/submit',
data: $scope.data
});
console.log('POST /submit ' + JSON.stringify($scope.data));
};
In browser's console everything is fine: $scope.data is valid; Node.js also responds with console.log, as expected, but writes undefined which means that, well, request.body is undefined.
What do I do wrong? How can I fix it?
If you're using Express 3 you shouldn't have to use the body-parser module as it is already bundled with Express 3 as express.bodyParser. You're getting an empty body because you're putting app.use(app.router) before the body parser.
app.configure(function() {
app.use(express.bodyParser());
app.use(app.router);
});
Which is why your other solution is working:
app.post('/submit', bodyParser.json(), function (req, res) {
Well, I just came up with solution, and it works. Here the app.post using body-parser is explained in few words. So I changed POST request handler definition to:
app.post('/submit', bodyParser.json(), function (req, res) {
console.log(req.body);
});
And now not only console.log(req.body) returns valid data, but it's deserialized into JSON correctly on the server without any extra code (which is, well, expected from Angular+Node pair).

Resources