How to get body parameters in node.js - javascript

Well I had just started programming in node.js. I am stuck at one place.
I am getting my request parameter like
response: --------------------------e2a4456320b2131c
sent
--------------------------e2a4456320b2131c
Content-Disposition: form-data; name="is_test"
true
--------------------------e2a4456320b2131c
Content-Disposition: form-data; name="success"
true
--------------------------e2a4456320b2131c--
How can i fetch all this params :
is_test , success and etc.
Here is my code :
var express = require('express'),
bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
exports.helloWorld = functions.https.onRequest((request, response) => {
var body = "";
request.on('data', function (data) {
body += data;
});
request.on('end', function() {
console.log('response: ' + body);
});
);

You need to configure the router to handle the request. Take a look at the hello world example of express docs http://expressjs.com/en/starter/hello-world.html
Moreover if you are sending data in the body you are looking for a http post method.
Example:
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
app.use(bodyParser.json());
app.post('/', function (req, res) {
const body = req.body;
/*Body logic here*/
res.status(200).end();
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
})

Related

res.send XML is giving empty Document in Express

I am trying simple api which return sml response :
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const libxmljs = require("libxmljs");
const PORT = process.env.PORT || 5000;
const app = express()
app.use(cors());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.send({ "message": "success" });
});
app.get('/api', (req, res) => {
var libxmljs = require("libxmljs");
var xml = '<?xml version="1.0" encoding="UTF-8"?>' +
'<root>' +
'<child foo="bar">' +
'<grandchild baz="fizbuzz">grandchild content</grandchild>' +
'</child>' +
'<sibling>with content!</sibling>' +
'</root>';
var xmlDoc = libxmljs.parseXml(xml);
// xpath queries
var gchild = xmlDoc.get('//grandchild');
console.log(gchild.text()); // prints "grandchild content"
var children = xmlDoc.root().childNodes();
var child = children[0];
console.log(child.attr('foo').value()); // prints "bar"
res.set('Content-Type', 'text/xml');
res.send(xmlDoc);
});
app.listen(PORT, () => {
console.log(`App running on PORT ${PORT}`)
});
here everthing is showing as expected in node console, but in the APi response i am not getting XML, I am getting this error:
This page contains the following errors:
error on line 1 at column 1: Document is empty
Below is a rendering of the page up to the first error.
Please help
I see that you copy the code from github repo.
You're sending as response the xml object, not the string....
Instead of
res.send(xmlDoc);
do
res.send(xml);

Pass sockets.io from express server file to route file

I would use sockets in a separate route file .
I'm using the method mentioned in this answer : Express 4 Routes Using Socket.io
I have copied exactly the same logic. In server file :
var http = require("http");
var admin = require('firebase-admin');
var firebase = require("firebase");
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var port = process.env.app_port || 8080; // set our port
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var server = app.listen(port);
var io = require("socket.io")(server);
var routerProj = require("./routes/routes")(io);
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT ,DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,*");
next();
});
var config = {
.... DB Configuration ....
};
firebase.initializeApp(config);
var serviceAccount = require("./ServiceAcountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://datatable-18f93.firebaseio.com"
});
io.on("connection", function (client) {
console.log("Un client est connecté !");
//routerProj(client);
});
app.use("/v1", routerProj, function (req) {
//Create HTTP server and listen on port 8000 for requests
});
My connection socket is working and the console.log runs in terminal
routes.js file
var express = require("express"); // call express
var router = express.Router(); // get an instance of the express Router
var admin = require("firebase-admin");
var returnRouter = function (client) {
router.use(function (req, res, next) {
// do logging
client.on('save-message', function (socket) { console.log("heheyy") })
});
router
.route("/")
.get(function (req, res, err) {
// Get a database reference to our posts
var db = admin.database();
var ref = db.ref("/");
// Attach an asynchronous callback to read the data at our posts reference
ref.once("value", function (snapshot) {
var list = [];
snapshot.forEach(function (elem) {
list.push(elem.val());
})
list = JSON.stringify(list);
//list = JSON.parse(list)
console.log(err);
//console.log(JSON.stringify(list))
res.send(list);
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
res.status(500).send(errorObject.code);
});
});
router
.route("/")
.post(function (req, res, err) {
console.log(req.body);
// Get a database reference to our posts
var db = admin.database();
var ref = db.ref("/");
ref.push(
{
"text": req.body.text
}
);
});
return router;
}
module.exports = returnRouter;
save-message is emit in Angular when my arr is running :
ngOnInit() {
this.socket.emit('save-message', { room: "hello" });
}
Save-message event is not getting read neither the routes file, In my angular application services does not get data from routes. and console.log in get and post routes does not work.
My question is how to get sockets working in a reparate file ?
You should move the socket.io listener outside of the express use route. It's not really clear why you would want it there as it will register a new listener every time someone makes a request to your v1 endpoint.
You likely aren't seeing the messages because the listener does not register until someone makes a request to the v1 endpoint and the client already sent its message.
var returnRouter = function (client) {
// do logging
client.on('save-message', function (socket) {
console.log("heheyy");
});
...
};

Express Post Request 404

I'll try to make this as to the point as possible. I am trying to make a post request to my express backend. All of the post requests here work, except for "/addpayment". Here is my file called 'router.js'
module.exports = function(app) {
app.post('/signin', requireSignin, Authentication.signin)
app.post('/signup', Authentication.signup)
app.post('/addpayment', function(req, res, next) {
res.send({ message: 'why................' })
})
}
Here is my main 'server.js' file
const express = require('express')
const http = require('http')
const bodyParser = require('body-parser')
const morgan = require('morgan')
const app = express()
const router = require('./router')
const mongoose = require('mongoose')
const cors = require('cors')
// DB Connect
mongoose.connect('mongodb://localhost/demo-app')
// App
app.use(morgan('combined'))
app.use(cors())
app.use(bodyParser.json({ type: '*/*' }))
router(app)
// Server
const port = process.env.PORT || 3090
const server = http.createServer(app)
server.listen(port)
console.log('Server has been started, and is listening on port: ' + port)
I get a 404 in postman, and inside my app browser console. I am using passport in my other routes. I already tried running it through passport when I have a JWT token, and same thing(a 404).
I have already looked at all Stack Overflow/Github posts on the first few pages of google results, with no solution for my use case.
I have made a simplified version of your server and everything works as expected. Only difference that I have made is that I am not creating http server like you, but just calling app.listen
here is working example
router.js
module.exports = function(app) {
app.post('/addpayment', function(req, res, next) {
res.send({message: 'why................'})
})
};
server.js
var express = require('express');
var router = require('./router');
var app = express();
router(app);
//init server
app.listen(3000, function() {
console.log("Server running on port 3000");
});

How to create Node server only for POST requests

I need to create a Node server only for receiving POST requests. With the information in the body of the request, I need to create a system call. How do I do so? So far, I only have:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser);
app.post('/', function(req, res){
console.log('POST /');
console.dir(req.body);
});
port = 3000;
app.listen(port);
console.log('Listening at http://localhost:' + port)
However, when I make a POST request to 127.0.0.1:3000, the body is undefined.
var request = require('request');
request.post(
'127.0.0.1:3000',
{ form: { "user": "asdf" } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
}
);
You've got a middleware problem here. The express.bodyparser() middleware is deprecated in Express 4.x. This means you should be using the standalone bodyparser middleware.
Oddly enough, you're importing the correct middleware by doing:
var bodyParser = require('body-parser');
However, you should be using it differently. Take a look at the docs and the example given:
var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data
app.post('/', function (req, res) {
console.log(req.body);
res.json(req.body);
})
var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data
app.post('/', function (req, res) {
console.log(req.body);
res.json(req.body);
})
In the newest version of express, express.bodyParser is not used. See the reference

Listen on HTTP and HTTPS for a single express app

Can I create an Express server listening on both HTTP and HTTPS, with the same routes and the same middlewares?
Currently I do this with Express on HTTP, with stunnel tunneling HTTPS to Express, but I prefer a pure Node solution.
I can do it with this code, but using the handle method that is marked as private:
var express = require( 'express' )
, https = require("https")
, fs = require( 'fs' );
var app = express.createServer();
// init routes and middlewares
app.listen( 80 );
var privateKey = fs.readFileSync( 'privatekey.pem' ).toString();
var certificate = fs.readFileSync( 'certificate.pem' ).toString();
var options = {key: privateKey, cert: certificate};
https.createServer( options, function(req,res)
{
app.handle( req, res );
} ).listen( 443 );
To enable your app to listen for both http and https on ports 80 and 443 respectively, do the following
Create an express app:
var express = require('express');
var app = express();
The app returned by express() is a JavaScript function. It can be be passed to Node’s HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app using the same code base.
You can do so as follows:
var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');
var app = express();
var options = {
key: fs.readFileSync('/path/to/key.pem'),
cert: fs.readFileSync('/path/to/cert.pem'),
ca: fs.readFileSync('/path/to/ca.pem')
};
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
For complete detail see the doc
As a possible update to this question, you might want to check out the changes here for express 3. The change document says:
The return value of express() is a JavaScript Function,
encapsulating everything that makes an Express app tick. This means
you can easily setup HTTP and HTTPS versions of your application by
passing it to node's http.createServer() and https.createServer():
In Express 3, express.createServer() is now express()
Here is a complete example for express 3:
var fs = require('fs')
, https = require('https')
, http = require('http')
, express = require('express')
, keys_dir = 'keys/'
, server_options = {
key : fs.readFileSync(keys_dir + 'privatekey.pem'),
ca : fs.readFileSync(keys_dir + 'certauthority.pem'),
cert : fs.readFileSync(keys_dir + 'certificate.pem')
}
, app = express();
app.configure(function(){
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session( { secret: '' } ));
app.use(app.router);
});
app.configure('development',function(){
app.use(express.static(__dirname + '/public'));
app.use(express.errorHandler({dumpExceptions: true, showStack:true}));
app.set('view options', { pretty: true });
});
app.get('/', function(req, res){
res.send('Hello World!');
});
https.createServer(server_options,app).listen(7000);
http.createServer(app).listen(8000);
You can share the implementation via something like:
var register = function (app) {
// config middleware
app.configure({
});
// config routes
app.get(...);
};
var http = express.createServer();
register(http);
http.listen(80);
var https = express.createServer({ key: /* https properties */ });
register(https);
https.listen(443);
You can use express and https in same port.
this works for me.
const express=require('express');
const app=express();
const cors=require('cors');
const path=require("path");
const routes=require('./routes/api');
const routerComplain=require('./routes/api');
const routerstores=require('./routes/api');
const routerstock=require('./routes/api');
const routerreport=require('./routes/api');
const routeritem=require('./routes/api');
const bodyParser=require('body-parser');
const routerRegister=require('./routes/api');
const mongoose=require('mongoose');
var server = require('http').Server(app);
var io = require('socket.io')(server);
require("dotenv").config();
mongoose.connect('mongodb://#################',{ useNewUrlParser: true },(err)=>{
if(!err){
console.log('db connected')
}else{
console.log('error in db')
}
});
mongoose.Promise = global.Promise;
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(cors({credentials: true, origin:'http://localhost:3000'}));
app.use(express.static(path.join(__dirname, "client", "build")))
app.use('/reg',routes);
app.use('/complain',routerComplain);
app.use('/register',routerRegister);
app.use('/stores',routerstores);
app.use('/reports',routerreport);
app.use('/stock',routerstock);
app.use('/items',routeritem);
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "client", "build", "index.html"));
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
})
const port = process.env.port||4000;
server.listen(port,function(){
console.log('now listening for request');
});
If you want to use the traditional two ports, one of the above solutions probably works, but using httpolyglot, you can really easily have http and https on the same port with the same middlewares.
https://github.com/mscdex/httpolyglot
Here's some skeleton code that worked for me:
var express = require('express');
var fs = require('fs');
var httpolyglot = require('httpolyglot');
var app = express();
const options = {
key: fs.readFileSync("/etc/ssl/certs/key"),
cert: fs.readFileSync("/etc/ssl/certs/cer.cer")
};
httpolyglot.createServer(options, app).listen(port);
and if you want http -> https forwarding, you can just add this middleware function before the createServer() call:
app.use(function(req, res, next) {
if (!req.secure ) {
res.redirect (301, 'https://' + req.hostname + ':port' + req.originalUrl);
}
next();
});
This can be set up on a custom port
Similar post
Can I configure expressjs to serve some pages over http and others over https?
Be aware that express now support creating Https servers with:
var app = require('express').createServer({ key: ... });

Categories

Resources