route (routes/account.js)
const express = require('express');
const router = express();
var account_controller = require('../controllers/accountController');
router.post('/account/Getuser', account_controller.get_user);
controller (controllers/accountController.js)
exports.get_user = function (req, res) {
res.send(req.body.name);
};
Postman POST Request body
{
"name":"Isaac Gyasi Nimako"
}
Error Report
Cannot read property 'name' of undefined
you probably don`t have body-parser
const bodyParser = require('body-parser')
router.use(bodyParser.json())
You have to use the body_parser library
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
here is a very simple example from my GitHub
https://github.com/odaymard/Restful-CRUD-API-with-Node.js-Express/blob/master/server/server.js
Related
I am not running into any errors but I am wondering if this is the correct way to use two or more route.js files using express.Router. Am I using module.exports = router correctly as they are in two separate files, or is there a different way?
app.js
const express = require("express");
const api = require("./routes/tracking.route");
const user = require("./routes/user.route");
const app = express();
app.use("/api", api);
app.use("/user", user);
tracking.route.js
const express = require("express");
const router = express.Router();
const tracking_controller = require("../controllers/tracking.controller");
router.get("/list", tracking_controller.tracking_list);
module.exports = router;
user.route.js
const express = require("express");
const router = express.Router();
const User = require("../models/user.model");
router.post("/signup", ...");
module.exports = router;
I'm trying to start my Node.js server, I have 2 files: my app.js
const express = require('express'),
app = express(),
bodyParser = require('body-parser'),
morgan = require('morgan'),
consign = require('consign'),
cors = require('cors'),
passport = require('passport'),
passportConfig = require('./passport')(passport),
jwt = require('jsonwebtoken'),
config = require('./index.js');
app.use(express.static('.'));
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(morgan('dev'));
app.use(cors());
app.use(passport.initialize());
app.set('playersecret', config.secret);
consign({ cwd: 'services' })
.include('Player/app/setup/')
.then('Player/app/api/')
.then('Player/app/routes/')
.into(app);
module.exports = app;
and /app/routes/auth.js
const models = require('#Player/app/setup');
module.exports = (app) => {
const api = app.PlayerAPI.app.api.auth;
app.route('/',).get((req,res) => res.send('Player API'));
app.post('/api/auth/',api.login(models.User));
}
and as I understood my routes are not imported to app.js, because if I write code right in app.js, it works fine.
How do I import it right?
The way you have your auth.js routes defined is that it accepts the app instance, so you would need to do the following in your app.js:
const express = require('express')
const authRoutes = require('./app/routes/auth.js')
const app = express()
// ...
authRoutes(app)
Alternatively you can just inline the require although I find that messy (personal opinion):
const express = require('express')
const app = express()
// ...
require('./app/routes/auth.js')(app)
A better approach would be to export a router object:
/app/routes/auth.js
const express = require('express')
const models = require('#Player/app/setup')
const api = require('./path/to/PlayerAPI.js')
const router = express.Router()
router.get('/', ...)
router.post('/', api.login(models.User))
module.exports = router
app.js
const express = require('express')
const authRoutes = require('./app/routes/auth.js')
const app = express()
// ...
app.use('/api/auth', authRoutes)
If you want to import a js file, you have to include the file name at the beginning of your app.js as show below.
var express = require('express')
var auth = require(./app/routes/auth.js)
you can know more about importing in javascript file in express.js official document file.
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);
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.
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)