Node.js code does not execute - node.js

I have written some Node.js code but when I run node index.js in my terminal it's just blank. My Node script does not even log to the console after creating the server or is responding with my index.html file. I even tried changing all 'req' and 'res' to 'request' and 'response'. Here's my code:
var http = require('http');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var urlparse = bodyParser.urlencoded({ extended: false });
http.createServer(function(request, response){
console.log('listening on port 8080');
app.on('request', function(request, response){
response.sendFile('./index.html');
});
app.post('/auth', urlparse, function(request, response){
var user = request.body.user;
var pass = request.body.pass;
});
}).listen(8080);
Pleas help. Thanks in advance.
EDIT: Anything inside the http.createserver(); does not execute because I tried logging another sentence outside the http.createServer(); and it logged!

Go ahead and try the following:
var http = require('http');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var urlparse = bodyParser.urlencoded({extended: false});
app.on('request', function (request, response) {
response.sendFile('./index.html');
});
app.post('/auth', urlparse, function (request, response) {
var user = request.body.user;
var pass = request.body.pass;
});
// Bind createServer with app:
http.createServer(app).listen(8080, function (request, response) {
console.log('listening on port 8080');
});
I expect that this should work for you.
Update:
The method mentioned, while works, has become outdated.
the recommended method is:
app.listen(8080, function () {
console.log('listening on port 8080');
});
Using this method allows you to skip requiring http.

Related

Issue to add socketio to API Express

i'm trying to add socket.io on my already existing NodeJS API REST Project.
var express = require('express')
var bodyParser = require('body-parser');
var https = require('https');
var http = require('http');
var fs = require('fs');
var router = require('./route/router');
require('dotenv').config();
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(require('helmet')());
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Authorization,Content-Type');
next();
});
router(app);
if (process.env.PRODUCTION === "false") {
http.createServer(app).listen(8080, function() {
console.log('8080 ok');
});
var io = require('socket.io')(http);
} else {
const options = {
cert: fs.readFileSync('./../../etc/letsencrypt/live/test.com/fullchain.pem'),
key: fs.readFileSync('./../../etc/letsencrypt/live/test.com/privkey.pem')
};
https.createServer(options, app).listen(8443, function() {
console.log('8443 ok');
});
var io = require('socket.io')(https);
}
io.sockets.on('connection', socket => {
console.log('socketio connected');
});
I have no error displayed (server side). But, when I tried on client side, this.socket = io('ws://localhost:8080/');, it's not working at all.
I get GEThttp://localhost:8080/socket.io/?EIO=3&transport=polling&t=NG6_U6i [HTTP/1.1 404 Not Found 1ms] browser console.
It seems that something is not ok with the server, but I can't find what's going on
Any idea ?
Thanks
Try this way, you need to include (I don't know if this is the correct word to use) the express server into the socket.io server.
const express = require('express');
const socketio = require('socket.io');
const port = process.env.PORT || 3006;
const app = express();
const server = app.listen(port, () => {
console.log(`App started on port ${port}`)
});
const io = socketio(server, { forceNew: true });
io.on('connect', (socket) => {
// do this
// do that
});
The code above is a skeleton of how express and socket.io are used together. Please modify it as per your needs.
Good luck.

Can not post to server using node express

I am trying to post data from postman to my node server, I keep getting 404.
Is my code setup correctly to receive post to http://localhost:8080/back-end/test and if not how can I fix it ?
var express = require('express');
var request = require('request');
var nodePardot = require('node-pardot');
var bodyParser = require('body-parser');
var rp = require('request-promise');
var app = express();
var port = process.env.PORT || 8080;
// Start the server
app.listen(port);
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({extended: true})); // support encoded bodies
console.log('Test server started! At http://localhost:' + port); // Confirms server start
var firstFunction = function () {
return new Promise (function (resolve) {
setTimeout(function () {
app.post('back-end/test.js', function (req, res) {
console.log(req.body);
var login = req.body.LoginEmail;
res.send(login);
resolve({
data_login_email: login
});
});
}, 2000);
});
};
I am posting LoginEmail and keep getting 404.
Move app.post() outside of the timeout, promise, and firstFunction.
There is no proceeding paths defined in your code, so the path must start with a /: /back-end/test.js. Don't forget the extension since you've defined it.

req.body undefined on server side

I am working on app which uses node, express, mysql on server side. i have written serveral APIs on server.js file and when i am trying to access those using Postman then req.body is always undefined.
this is my server.js configuration.
var express = require('express');
var mysql = require('mysql');
var cors = require('cors');
var bodyParser = require('body-parser');
var wrench = require("wrench");
var fs = require('fs');
var path = require("path");
var mkdirp = require('mkdirp');
var walk = require('walk');
var fse = require('fs-extra');
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var crypto = require('crypto');
app.use(cors());
app.use(bodyParser.urlencoded({limit: '50mb',extended: false}));
app.use(bodyParser.json({limit: '50mb'}));
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'pass',
database: 'dbname'
});
connection.connect(function(err) {
if (!err) {
console.log("Database is connected ... \n\n");
} else {
console.log("Error connecting database ... \n\n");
}
});
app.post('/urlreq', function(req, res){
console.log(req.body);
}
app.listen(3000, function(){
console.log("Rest Demo Listening on port 3000");
});
When i am trying send something in body in Postman then req.body is coming empty on server side.
If you are sending multipart/form-data, it doesn't work because bodyparser doesn't handle this body type.
In this case adding the following line should fix it:
app.use(multipartMiddleware);
Form the docs:
multipart/form-data is the default encoding a web form uses to transfer data
Try add:
var express = require('express');
var app = express();
[...]
// Last stack
app.listen(3000, function(){
console.log("Rest Demo Listening on port 3000");
});
You can use as a middleware also. Also listen on a port. add following lines in your code -
var app = express();
app.use(function(req, res, next) {
console.log('Current User:', req.body);
next();
});
app.post('/url', function(req,res){
console.log(req.body)
});
app.listen(3000, function(){
console.log('Express server listening on port 3000');
});

Not able to solve Express Middleware issue

My first piece of code below:
var express = require('express');
var app = express.createServer(express.logger());
app.get('/', function(request, response){
response.send('Hello World 2');
});
var port = process.env.PORT || 5000;
app.listen(port, function(){
console.log("Listening on " + port);
});
Threw up the error: "Most middleware (like logger) is no longer bundled with Express and must be installed separately"
So I looked at StackOverflow, did npm install morgan, and changed my code to:
var express = require('express');
var logger = require('morgan');
var app = express.createServer(logger());
app.get('/', function(request, response){
response.send('Hello World 2');
});
var port = process.env.PORT || 5000;
app.listen(port, function(){
console.log("Listening on " + port);
});
Now I get this error:
var app = express.createServer(logger());
^
TypeError: Object function createApplication() {
var app = function(req, res, next) {
app.handle(req, res, next);
};
mixin(app, proto);
mixin(app, EventEmitter.prototype);
app.request = { __proto__: req, app: app };
app.response = { __proto__: res, app: app };
app.init();
return app;
} has no method 'createServer'
That is because createServer method has been removed from express.
use
app = express();
app.use(logger())
instead of
app = express.createServer(logger())
Many things got changed from express 3.0 to 4.0. You should have a look here
You should create app with express(). Afterwards, you can setup any middleware (like morgan in this case) with app.use:
var express = require('express');
var logger = require('morgan');
var app = express();
app.use(logger());
...
app.use() documentation: http://expressjs.com/4x/api.html#app.use. (Linking to Express 4.x documentation as not explicit what Express version you're running).
There is an exact same example like the one I wrote above in Morgan's README in GitHub.

Accessing >=2 collections from the same db connection using Mongo-lite results in error

I am trying to access more than a single mongo collection from the same db connection using mongo-lite. Here is a sample express app.
var express = require('express') ;
var app = express();
var http = require('http');
var mongolite = require('mongo-lite');
db = mongolite.connect("mongodb://localhost/fnard", ['col1','col2']);
app.use(express.bodyParser());
app.use(app.router);
app.get('/', function(request, response){
db.collection('col1').insert({hi:5},function(){});
db.collection('col2').insert({hi:5},function(){});
console.log(request.body); // your JSON
response.send(request.body); // echo the result back
});
http.createServer(app).listen(3000, function () {
console.log('Express server listening on port ' + '3000');
});
Here is the error I am getting on doing a GET on /:
Error: A Server or ReplSetServers instance cannot be shared across multiple Db instances
However if I use the following code the GET inserts the documents as expected
var express = require('express') ;
var app = express();
var http = require('http');
var mongolite = require('mongo-lite');
db = mongolite.connect("mongodb://localhost/fnard", ['col1']);
db2 = mongolite.connect("mongodb://localhost/fnard", ['col2']);
app.use(express.bodyParser());
app.use(app.router);
app.get('/', function(request, response){
db.collection('col1').insert({hi:5},function(){});
db2.collection('col2').insert({hi:5},function(){});
console.log(request.body); // your JSON
response.send(request.body); // echo the result back
});
Do I need to really create a new connection for each collection I want to access?
The mongo-lite docs seem to suggest that this isn't the case - the .connect() option lets you specify which collections you want to use but it doesn't seem to work.
mongo-lite docs link
A race condition is giving you the error. The following works for me:
var express = require('express');
var app = express();
var http = require('http');
var mongolite = require('mongo-lite');
db = mongolite.connect("mongodb://localhost/fnard", ['col1','col2']);
app.use(express.bodyParser());
app.use(app.router);
app.get('/', function(request, response){
db.collection('col1').insert({hi:5},function(){
db.collection('col2').insert({hi:5},function(){
console.log(request.body); // your JSON
response.send(request.body); // echo the result back
});
});
});
http.createServer(app).listen(3000, function () {
console.log('Express server listening on port ' + '3000');
});
You need to nest your callbacks. Or, you can use a library like async:
var express = require('express');
var async = require( 'async' );
var app = express();
var http = require('http');
var mongolite = require('mongo-lite');
db = mongolite.connect("mongodb://localhost/fnard", ['col1','col2']);
app.use(express.bodyParser());
app.use(app.router);
app.get('/', function(request, response){
async.series( [
// First insert
function ( callback ) {
db.collection('col1').insert({hi:5},callback);
},
// Second insert
function ( callback ) {
db.collection('col2').insert({hi:5},callback);
}
// Send response
], function ( error, results ) {
console.log(request.body); // your JSON
response.send(request.body); // echo the result back
} );
});
http.createServer(app).listen(3000, function () {
console.log('Express server listening on port ' + '3000');
});

Resources