server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var session = require('express-session');
var fs = require('fs');
var router = require('./router/main')(app, fs);
var server = app.listen(3000, function(){
console.log('Express server has started on port 3000');
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
router/main.js
module.exports = function(app, fs)
{
app.post('/addUser/', function(req, res){
console.log(req.body);
});
}
I use postman tool!! requets param {"password" : "pass","name" : "dltlsdn"}
but... req.body is undefind.... why..??
Reorder the app.use statement. Earlier you were processing the request before passing through the body-parser.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var session = require('express-session');
var fs = require('fs');
//body parser before routes
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
var router = require('./router/main')(app, fs);
var server = app.listen(3000, function(){
console.log('Express server has started on port 3000');
});
Hope it helped you.
Related
I am using router in my NodeJs app.When I am trying to navigate it is unable to navigate to the given page.
Register.js is placed in routes folder and server.js is placed in parent directory.
Here is my code:
Server.js
const express = require('express');
const app = express();
app.set('view engine','ejs');
app.use(require('./routes/register'));
const port = process.env.PORT || 3000;
app.listen(port, (req,res) => {
console.log("Server is running at:", +port);
});
Register.js
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
var app = express();
router.use(bodyParser.json);
router.use(bodyParser.urlencoded({extended:true}));
router.get('/users', (req,res) => {
console.log('Hello there');
});
module.exports = router;
Now when I run this code and go to localhost:3000/users nothing happens and not even error shows in console.
Please let me know what I am doing wrong in above code.
Use router.use(bodyParser.json()); in register.js.
You have used body-parser at wrong place. Also you should initiate those with express instances always.
Also check your file name you have imported. Reigster -> register
Updated code:
Server.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.set('view engine','ejs');
app.use(require('./Register'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
const port = process.env.PORT || 3000;
app.listen(port, (req,res) => {
console.log("Server is running at:", +port);
});
Register.js
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
router.get('/users', (req,res) => {
console.log('Hello there');
res.sendStatus(200)
});
module.exports = router;
Hi I have these two files, and trying to call index.js from server.js which works fine and is printing 'on the other side of the code' but it is not going inside the app.get function. Please advise what I am doing wrong
Server.js
const express = require("express")
const bodyParser = require("body-parser")
const app = express()
var routes = require('./api/index.js')
const PORT = process.env.PORT || 3000
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use('/t', require('./api/index')(app))
var server = app.listen(PORT, function (){
var host = server.address().address
var port = server.address().port
console.log('Middle ware started on address http://%s:%s',host,port)
})
index.js
const express = require('express')
module.exports = function(app) {
console.log('we are in other part of code')
app.get('/',function(req,res){
console.log('we are there')
console.log(res)
})
}
You should use express Router class to create modular route handlers:
Server.js
const express = require("express")
const bodyParser = require("body-parser")
const app = express()
var routes = require('./api/index.js')
const PORT = process.env.PORT || 3000
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use('/t', routes)
app.listen(PORT, function (){
var host = server.address().address
var port = server.address().port
console.log('Middle ware started on address http://%s:%s',host,port)
})
index.js
const express = require('express')
const router = express.Router()
router.get('/',function(req,res){
console.log('we are there')
res.send('successfully get /t')
})
module.exports = router;
Your approach is not right try this way
server.js
const express = require("express")
const bodyParser = require("body-parser")
const app = express();
const PORT = process.env.PORT || 3000
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use('/t', require('./api/index.js'));
var server = app.listen(PORT, function (){
var host = server.address().address
var port = server.address().port
console.log('Middle ware started on address http://%s:%s',host,port)
})
index.js
const express = require('express');
router=express.Router();
router.get('/',function(req,res){
console.log('we are there')
console.log(res)
res.send('success')
});
module.exports=router;
Server.js
const express = require("express")
const bodyParser = require("body-parser")
const app = express()
var routes = require('./api/index.js')(app) // Pass the app
const PORT = process.env.PORT || 3000
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use('/t', routes) // change this to routes
var server = app.listen(PORT, function (){ var host = server.address().address var port = server.address().port
console.log('Middle ware started on address http://%s:%s',host,port) })
index.js
const express = require('express')
module.exports = function(app) {
console.log('we are in other part of code')
app.get('/',function(req,res){
console.log('we are there')
console.log(res)
res.json({success : true});
})
}
Here is an image of the error. I developed an application on AngularJS, and when I run node server by using public wifi my application is running fine. However, when I run it on org network/company wifi my application doesn't work. Any help?
server.js code
var express = require("express");
var open = require("open");
var bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");
var fs = require("fs");
var path = require("path");
var auth = require("./api/auth");
//var users = require("./api/users");
var transactions = require("./api/transactions");
//var serviceTypes = require("./api/serviceTypes");
var app = express();
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.static("boilerplate"));
app.use(express.static("./"));
app.listen(3000, function () {
console.log("server is running on port:3000");
open("http://localhost:3000/");
});
app.get("/", function (req, res) {
res.sendFile(path.join(__dirname, "boilerplate/index.html"));
});
app.use("/auth", auth);
//app.use("/users", users);
app.use("/transactions", transactions);
//app.use("/servicetypes", serviceTypes);
I am working on a express project where subdomains are used.
Now the problem i am facing is that my domain name is ("companyName.co.in") and my node JS code is considering companyName as the subdomain.
Here is my code:
server.js
var express = require('express');
var app = express();
var subdomain = require('express-subdomain');
var bodyParser = require('body-parser');
var path = require('path');
var expressValidator = require('express-validator');
var expressJwt = require('express-jwt');
var jwt = require('jsonwebtoken');
var cors = require('cors');
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
app.use(cors());
//app.use(cookieParser());
app.use(express.static('../app'));
app.use(express.static('static/'));
app.use('/api/user',require('./controllers/user.controller'));
var server = app.listen(3000,function(){
console.log('Server listening at 3000');
});
user.controller.js
var express = require('express');
var router = express.Router();
router.get("/details", getUserDetails);
function getUserDetails(req, res) {
var subdomain = (req.subdomains.length > 0) ? req.subdomains[0] : '';
console.log(subdomain)
}
module.exports = router;
So when i call the api/user/details i find that it gives the companyName as the subdomain.
like: requesting from "companyName.co.in"
subdomain should be null but it gives me subdomain as companyName.
Can you please help how can i let the node server know that "companyName.co.in" this is the host and also allow "*.companyName.co.in" where the subdomain can be anything.
You can solve this in your case by setting the 'subdomain offset' express app setting to 3.
http://expressjs.com/en/4x/api.html#app.settings.table
var express = require('express');
var app = express();
app.set('subdomain offset', 3);
How can i read cookie on node js ??
var socket = require( 'socket.io' );
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = socket.listen( server );
var port = process.env.PORT || 8000;
var mysql = require('mysql');
function parseCookies (request) {
var list = {},
rc = request.headers.cookie;
rc && rc.split(';').forEach(function( cookie ) {
var parts = cookie.split('=');
list[parts.shift().trim()] = decodeURI(parts.join('='));
});
return list;
}
http.createServer(function (request, response) {
// To Read a Cookie
var user_id= cookies.realtimeid;
console.log(user_id);
});
server.listen(port, function () {
console.log('Server listening at port %d', port);
var cookies = parseCookies();
console.log(cookies);
});
I am new on node and socket. I have to read cookie value that is set by codeignter.
How can i send header request on parseCookies from server.listen.
I see you are using express, so I suggest you to use the very well known module for it. cookie-parser https://www.npmjs.com/package/cookie-parser
Installation
npm install cookie-parser
HOW TO USE IT
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
So basically after your mysql require you can do app.use(cookieParser())
And then in every request you do in the req variable you will find the cookies with req.cookies
Example
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
app.get('/', function(req, res) {
console.log("Cookies: ", req.cookies)
})
app.listen(8080)