Cant use parseInt() in LocalHost NodeJS - Body Parser - node.js

im actully new in node js so i got this error while using parseInt or Number() in my server
code :
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/bmicalculator", function(req, res) {
res.sendfile(__dirname + "/index.html");
});
app.post("/bmicalculator", function(req, res) {
var nm1 = parseInt(req.body.num1); // <-- here the error
var nm2 = parseInt(req.body.num2); // <-- here the error
var result = nm1 + nm2 * nm2;
res.send(result);
});
app.listen(3000, function() {
console.log("server started");
});
here the error from Browser & Terminal :
RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: 29636
at ServerResponse.writeHead (_http_server.js:248:11)
at ServerResponse._implicitHeader (_http_server.js:239:8)
at ServerResponse.end (_http_outgoing.js:763:10)
at ServerResponse.send (C:\Users\Amir\Desktop\Calculator\node_modules\express\lib\response.js:221:10)
at C:\Users\Amir\Desktop\Calculator\calculator.js:16:9
at Layer.handle [as handle_request] (C:\Users\Amir\Desktop\Calculator\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Amir\Desktop\Calculator\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\Amir\Desktop\Calculator\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\Amir\Desktop\Calculator\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\Amir\Desktop\Calculator\node_modules\express\lib\router\index.js:281:22

This error seems to be caused by the method res.send. In old version of Express (v3),
the first argument used to be http status code but in your case, it's a big number (invalid http status code), hence the error is thrown.
in order to fix this, you can do either
upgrade to a newer version of express.
do this res.send(200, result) instead.
See the Express v3 docs here for reference: https://expressjs.com/en/3x/api.html#res.send
res.send([body|status], [body])
Send a response.
res.send(Buffer.from('whoop'))
res.send({ some: 'json' })
res.send('<p>some html</p>')
res.send(404, 'Sorry, we cannot find that!')
res.send(500, { error: 'something blew up' })
res.send(200)
You can see your case is same as the last example but your first argument is a big number 29636, which is invalid status code.

Add:
app.use(bodyParser.json());
And change the reponse to:
res.send(200, result);

Related

Req.body of a twilio webhook request is undefined node js

I tried following this twilio article:
https://www.twilio.com/blog/parsing-an-incoming-twilio-sms-webhook-with-node-js
The following is my server in its entirety
// Imports
const http = require('http')
const express = require('express')
const app = express()
const port = 80
const MessagingResponse = require('twilio').twiml.MessagingResponse;
// Static Files
app.use(express.static('public'))
// Set views
app.set('views', './views')
app.post('/sms', (req, res) => {
const twiml = new MessagingResponse();
// Access the message body and the number it was sent from.
console.log(req.IncomingMessage.body)
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(twiml.toString());
});
// Listen on port
app.listen(port, () => {
console.log(`Running on port ${port}`)
})
I have the webhook of my twilio phone posting to "http://{domain}.com/sms"
Every time I send a text to my twilio phone, I get the following error:
TypeError: Cannot read property 'body' of undefined
at app.post (/home/ubuntu/{domain}/server.js:24:37)
at Layer.handle [as handle_request] (/home/ubuntu/{domain}/node_modules/express/lib/router/layer.js:95:5)
at next (/home/ubuntu/{domain}/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/ubuntu/{domain}/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/ubuntu/{domain}/node_modules/express/lib/router/layer.js:95:5)
at /home/ubuntu/{domain/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/ubuntu/{domain}/node_modules/express/lib/router/index.js:335:12)
at next (/home/ubuntu/{domain}/node_modules/express/lib/router/index.js:275:10)
at serveStatic (/home/ubuntu/{domain}/node_modules/serve-static/index.js:75:16)
at Layer.handle [as handle_request] (/home/ubuntu/{domain}/node_modules/express/lib/router/layer.js:95:5)
I don't think the req object has any property called IncomingMessage. Instead you could try:
console.log(`Incoming message from ${req.body.From}: ${req.body.Body}`);
So based on the twilio specs, the endpoint would look like:
app.post('/sms', (req, res) => {
const twiml = new MessagingResponse();
// Access the message body and the number it was sent from.
console.log(`Incoming message from ${req.body.From}: ${req.body.Body}`);
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(twiml.toString());
});
Since the message body is in the req.body.Body parameter, so console logging this property will show you the message text.
First answer is correct,
console.log(`Incoming message from ${req.body.From}: ${req.body.Body}`);
but I had to make sure to set the express urlencoding or else req.body came back as undefined.
app.use(
express.urlencoded({
extended: true,
})
);
I'm not sure if this is correct but when I'm using express I use req.body.IncomingMessage
console.log(req.body.IncomingMessage)

Nodejs Express POST 404 Not Found error on live, working on localhost

I recently changes my domain (and SSL certificate) on my live server and since then I have been not able to POST to my node.js express app.
GET is working perfectly fine and POST is working on localhost but my live app is returning a 404 error whenever I send a POST request.
Error stack trace shows:
Error: Not Found
at /opt/bitnami/apps/tot/app.js:63:15
at Layer.handle [as handle_request] (/opt/bitnami/apps/tot/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:317:13)
at /opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:335:12)
at next (/opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:275:10)
at allowCrossDomain (/opt/bitnami/apps/tot/app.js:56:5)
at Layer.handle [as handle_request] (/opt/bitnami/apps/tot/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:317:13)
at /opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:335:12)
at next (/opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:275:10)
at SendStream.error (/opt/bitnami/apps/tot/node_modules/serve-static/index.js:121:7)
at SendStream.emit (events.js:200:13)
at SendStream.error (/opt/bitnami/apps/tot/node_modules/send/index.js:270:17)
at SendStream.onStatError (/opt/bitnami/apps/tot/node_modules/send/index.js:421:12)
I have a very simple app:
require('dotenv').config();
const express = require('express');
const app = express();
const helmet = require('helmet');
//const morgan = require('morgan'); //logging requests to console
//const fileUpload = require('express-fileupload');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const path = require('path');
const startupDebugger = require('debug')('tot:startup');
const mongoDebugger = require('debug')('tot:mongo');
const port = process.env.WEB_PORT;
// configure middleware
app.set('port', process.env.port || port); // set express to use this port
//app.set('views', __dirname + '/views'); // set express to look in this folder to render our view
app.set('view engine', 'ejs'); // configure template engine
app.use(helmet());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // parse form data client
app.use(express.static(path.join(__dirname, 'public'))); // configure express to use public folder
//app.use(fileUpload()); // configure fileupload
const urlencodedParser = bodyParser.urlencoded({ extended: false })
// --- Routes ---
const {getHomePage} = require('./routes/index');
const {playground} = require('./routes/playground');
const {getMessage} = require('./routes/slack/events-api');
const {getComponent} = require('./routes/slack/interactive-components');
const {renderSurvey} = require('./routes/feedback/survey');
const {score} = require('./routes/feedback/score-api');
app.get('/', getHomePage);
app.get('/playground', playground);
// Slack APIs
app.post('/slack/events-api', getMessage);
app.post('/slack/interactive-components', urlencodedParser, getComponent);
//Feedback
app.get('/feedback/survey/:team_id/:user_id/:question_id/:date', renderSurvey);
app.post('/feedback/score', score);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
console.error(err.stack);
next(err);
});
app.listen(port, () => { startupDebugger(`Server running on port: ${port}`); });
mongoose.connect(process.env.MONGO, { useNewUrlParser: true })
.then(() => mongoDebugger('Connected to MongoDB.'))
.catch(error => mongoDebugger('MongoDB Error: '+error));
Here is an example for /slack/events-api
getMessage: async function (req, res) {
//console.log(req);
let payload = req.body;
console.log('Payload:');
console.dir(payload, {depth: null});
slackDebugger('Slack Event API Challange Request');
res.render('slack/events-api.ejs', {
title: "Slack Bot"
, output: req.body.challenge
});
}
}
When I post via Postman locally it works fine:
[nodemon] starting `node app.js`
tot:startup Server running on port: 3000 +0ms
tot:mongo Connected to MongoDB. +0ms
Payload:
{ token: 'Jhj5dZrVaK7ZwHHjRyZWjbDl',
challenge: '3eZbrw1aBm2rZgRNFdxV2595E9CY3gmdALWMmHkvFXO7tYXAYM8P',
type: 'url_verification' }
tot:slack Slack Event API Challange Request +0ms
On the live server:
[nodemon] starting `node app.js`
tot:startup Server running on port: 3000 +0ms
tot:mongo Connected to MongoDB. +0ms
Error: Not Found
at /opt/bitnami/apps/tot/app.js:63:15
at Layer.handle [as handle_request] (/opt/bitnami/apps/tot/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:317:13)
at /opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:335:12)
at next (/opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:275:10)
at allowCrossDomain (/opt/bitnami/apps/tot/app.js:56:5)
at Layer.handle [as handle_request] (/opt/bitnami/apps/tot/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:317:13)
at /opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:335:12)
at next (/opt/bitnami/apps/tot/node_modules/express/lib/router/index.js:275:10)
at SendStream.error (/opt/bitnami/apps/tot/node_modules/serve-static/index.js:121:7)
at SendStream.emit (events.js:200:13)
at SendStream.error (/opt/bitnami/apps/tot/node_modules/send/index.js:270:17)
at SendStream.onStatError (/opt/bitnami/apps/tot/node_modules/send/index.js:421:12)
I cannot for the life of me work out why this has suddenly stopped working on live since updating the live URL/SSL.
If anybody can point me in the right direction that would be amazing.

NodeJS TypeError: Cannot read property of undefined while accessing cloudant

I am trying to get a basic understanding of how CRUD operations with db works with node js.
I have created two separate files - server.js and app.js.
server.js contains code for accessing the database and app.js got a reference to server.js through 'require'.
Below is my code for server.js :
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8999;
var router = express.Router();
app.use(cors());
app.use('/cloudApi', router);
app.listen(port);
console.log('REST API is runnning at ' + port);
var dbp = "users";
var Users;
function initCloudant() {
var cloudantURL = appEnv.services.cloudantNoSQLDB[0].credentials.url || appEnv.getServiceCreds("users-cloudant").url;
var Cloudant = require('cloudant')({
url: cloudantURL,
plugin: 'retry',
retryAttempts: 10,
retryTimeout: 500
});
Users = Cloudant.use(dbp);
}
router.route('/tests').get(function (req, res) {
console.log("Inside tests api");
Users.find({
selector: {
"testName":"abc"
},
}, function(err, result) {
res.send(result);
});
});
when I run this using command : node server.js, everything works fine for me.
I can access the api through postman as well.
in my app.js, I have given refernce to this:
var server= require('./dir/server.js');
when I run the command- node app.js
and try to hit the api, I get error as :
TypeError: Cannot read property 'find' of undefined
at C:\Users\nodeApp\dir\server.js:80:13
at Layer.handle [as handle_request] (C:\Users\nodeApp\node_modules\express\lib\router\layer.js:
95:5)
at next (C:\Users\nodeApp\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\nodeApp\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\nodeApp\node_modules\express\lib\router\layer.js:
95:5)
at C:\Users\nodeApp\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\nodeApp\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\nodeApp\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\nodeApp\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\anodeApp\node_modules\express\lib\router\index.js:47:12)
I dont know what point I am missing so that the apis can work.
Your initCloudant method is never getting executed it seems.
call initCloudant from success callback of get method like below:
router.route('/tests').get(function (req, res) {
initCloudant() //call it here
console.log("Inside tests api");
Users.find({
selector: {
"testName":"abc"
},
}, function(err, result) {
res.send(result);
});
Or alternatively intialize your User object properly to default properties.

node.js TypeError: undefined is not a function on app.get("/")

I'm trying out node.js and some hello world examples and I'm getting this error
TypeError: undefined is not a function
at c:\users\admin\documents\visual studio 2015\Projects\TheBoard\TheBoard\server.js:10:13
at Layer.handle [as handle_request] (c:\users\admin\documents\visual studio 2015\Projects\TheBoard\TheBoard\node_modules\express\lib\router\layer.js:95:5)
at next (c:\users\admin\documents\visual studio 2015\Projects\TheBoard\TheBoard\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch (c:\users\admin\documents\visual studio 2015\Projects\TheBoard\TheBoard\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (c:\users\admin\documents\visual studio 2015\Projects\TheBoard\TheBoard\node_modules\express\lib\router\layer.js:95:5)
at c:\users\admin\documents\visual studio 2015\Projects\TheBoard\TheBoard\node_modules\express\lib\router\index.js:277:22
at Function.process_params (c:\users\admin\documents\visual studio 2015\Projects\TheBoard\TheBoard\node_modules\express\lib\router\index.js:330:12)
at next (c:\users\admin\documents\visual studio 2015\Projects\TheBoard\TheBoard\node_modules\express\lib\router\index.js:271:10)
at expressInit (c:\users\admin\documents\visual studio 2015\Projects\TheBoard\TheBoard\node_modules\express\lib\middleware\init.js:33:5)
at Layer.handle [as handle_request] (c:\users\admin\documents\visual studio 2015\Projects\TheBoard\TheBoard\node_modules\express\lib\router\layer.js:95:5)
Here's my code
var http = require("http");
var express = require("express");
var app = express();
app.get("/",
function(res, req) {
res.send("<html><body><h1>Express</h1></body></html>");
});
app.get("/api/users",
function(req, res) {
res.send({ name: "Louis", isValid: true, group: "Admin" });
});
var server = http.createServer(app);
server.listen(3000);
I'm only getting the error when I hit http://localhost:3000/
I do not get any error when I hit http://localhost/api/users
problem in a ordering of parameter.. req object doesn't have any send function.
var http = require("http");
var express = require("express");
var app = express();
app.get("/",
function(req, res) {
res.send("<html><body><h1>Express</h1></body></html>");
});
app.get("/api/users",
function(req, res) {
res.send({ name: "Louis", isValid: true, group: "Admin" });
});
var server = http.createServer(app);
server.listen(3000);
Your function for app.get("/") is not correct. The order in which you have passed the arguments is not right. The correct way is to first give request object and then the response object. The correct way is to write like this:
app.get("/",
function(req, res) {
res.send("<html><body><h1>Express</h1></body></html>");
});
Hope this might work for you. :)

Why isn't node's 'fs' module loading? (error: Object #<Object> has no method 'readFile')

For some reason, my express server is not loading the file system 'fs' module correctly. I'm using the angular-fullstack yeoman generator. My system is Windows 7 with node version 0.10.35, npm version 2.1.18, and the latest version of angular-fullstack. I've tried all sorts of things, like both 32-bit and 64-bit and updating everything.
routes.js (which has other routes that load fine):
'use strict';
var errors = require('./components/errors');
var express = require('express');
var fs = require('fs');
module.exports = function(app) {
app.route('/pdf/*')
.get(function(req, res) {
var pdfPath = app.get('appPath') + '/assets/pdf/test.pdf';
fs.readfile(pdfPath, function(error, data) {
res.setHeader('Content-Disposition', 'attachment; filename="test.pdf"');
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Length', data.length);
res.status(200).end(data, 'binary');
});
});
// All undefined asset or api routes should return a 404
app.route('/:url(api|auth|components|app|bower_components|assets)/*')
.get(errors[404]);
// All other routes should redirect to the index.html
app.route('/*')
.get(function(req, res) {
res.sendfile(app.get('appPath') + '/index.html');
});
};
Server error:
TypeError: Object #<Object> has no method 'readfile'
at Object.handle (C:\Projects\policy5\server\routes.js:19:7)
at next_layer (C:\Projects\policy5\node_modules\express\lib\router\route.js:103:13)
at Route.dispatch (C:\Projects\policy5\node_modules\express\lib\router\route.js:107:5)
at c (C:\Projects\policy5\node_modules\express\lib\router\index.js:195:24)
at Function.proto.process_params (C:\Projects\policy5\node_modules\express\lib\router\index.js:251:12)
at next (C:\Projects\policy5\node_modules\express\lib\router\index.js:189:19)
at next (C:\Projects\policy5\node_modules\express\lib\router\index.js:166:38)
at trim_prefix (C:\Projects\policy5\node_modules\express\lib\router\index.js:228:11)
at c (C:\Projects\policy5\node_modules\express\lib\router\index.js:198:9)
at Function.proto.process_params (C:\Projects\policy5\node_modules\express\lib\router\index.js:251:12)
GET /pdf/test.pdf 500 2ms - 934b
It's readFile() not readfile() (uppercase F vs lowercase f).

Resources