How to get base path from Node js Side? - javascript

Note: I tried all questions & answer related to this topic but am not able to resolve the issue.
I want to base path from Node Js Side. Example below. I using [angular js + NodeJS/ExpressJS ]
<base href="/Tutorial/Routing/StateProvider/" />
html
<!DOCTYPE html>
<html ng-app="myapp2">
<title>Index | Angular Js</title>
<base href="/Tutorial/Routing/StateProvider/" />
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<!--<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.2/angular-ui-router.js"></script>
<script src="StateProviderController.js"></script>
<body >
<nav class="navbar navbar-default row">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" ui-sref="TutorialHome"> State Routing</a>
</div>
<ul class="nav navbar-nav">
<li><a ui-sref="Profile">Profile</a></li><!--State Transition on click-->
<li><a ui-sref="Account">Account</a></li><!--State Transition on click-->
<li><a ui-sref="Setting">Setting</a></li><!--State Transition on click-->
<li style="float: right;"><a ui-sref="Home">Home</a></li><!--State Transition on click-->
</ul>
</div>
</nav>
Controller Js
var myapp= angular.module('myapp2',["ui.router"]);
myapp.config(function($stateProvider,$urlRouterProvider,$locationProvider,$urlMatcherFactoryProvider){
$urlMatcherFactoryProvider.strictMode(false);
$stateProvider
.state('TutorialHome', {
url:'/index',
templateUrl:'/index.html'
})
.state('Home',{
url:'/',
templateUrl:'http://localhost:3000/'
})
.state('Profile',{
url:'/Profile',
templateUrl:'Profile.html'
})
.state('Account',{
url:'/Account',
templateUrl:'Account.html'
})
.state('Setting',{
url:'/Setting',
templateUrl:'Setting.html'
})
.state('Setting.StudenListing', {
url:'/StudenList',
views: {
'StudenListing': {
templateUrl: 'StudenListing.html',
controller:'StudentListingData'
}
}
})
.state('Setting.StudenListing.StudentList',{
url:'/StudenList/:StudentID',
/* templateUrl: 'StudentDetails.html',
controller:'StudentDetails'*/
views:{
'StudentDetails': {
templateUrl: 'StudentDetails.html',
controller:'StudentDetails'
}
}
})
;
// $urlRouterProvider.otherwise('/index');
$locationProvider.html5Mode(true);
});
myapp.controller('StateProviderCtrl',function($scope){
$scope.message ="Welcome To State Provider Page";
});
myapp.controller('StudentListingData',function($scope,$http){
console.log('test');
$http.get('/StudenRecordData').success(function(response){
// console.log(response);
$scope.StudentRecorddata =response;
})
});
myapp.controller('StudentDetails',function($scope,$http,$stateParams){
$scope.StudentID = $stateParams.StudentID;
//console.log( $scope.StudentID);
$http.get('/StuentRecordSearch/'+ $stateParams.StudentID).success(function(response){
//console.log(response);
$scope.StuentDetails =response[0];
})
});
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var url =require('url');
var index = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.get('/*',function(req,res){
console.log('node js request call');
var pathname2 = url.parse(req.url);
console.log('pathname-1:'+pathname2);
console.log('pathname-2:'+__dirname);
console.log('pathname-3:'+__filename);
console.log(url.parse(index));
//console.log('basw path:'+process.env.PWD);
res.sendFile(path.resolve('public/index.html'));
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;

Use cheerio module for extracting the DOM at server side.
create utility.js
var cheerio = require('cheerio');
var fs = require('fs');
var utility = {
getBasePath : function (filePath) {
fs.readFile(filePath, function (err, html) {
if (err) { throw err; }
else {
$ = cheerio.load(html.toString());
return $('base').attr('href');
}
});
}
};
module.exports = utility;
update your app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var url =require('url');
var index = require('./routes/index');
var app = express();
var utility = require('./utility'); /// load your module
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.get('/*',function(req,res){
console.log('node js request call');
var basePath = utility.getBasePath('./index'); /// call your funtion here ///
var pathname2 = url.parse(req.url);
console.log('pathname-1:'+pathname2);
console.log('pathname-2:'+__dirname);
console.log('pathname-3:'+__filename);
console.log(url.parse(index));
//console.log('basw path:'+process.env.PWD);
res.sendFile(path.resolve('public/index.html'));
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development

Related

Route Express.JS Post parameters

I'm trying to get post parameters into a express.js code...
[...].post(function(req, res){} method doesn't work.
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'vash');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use('/', index);
app.use('/users', users);
app.route('/a/:value').get(function (req, res) {
res.render('index', {title: req.params.value});
});
//app.route('/').post doesn t work.. the ide (WebStorm) can't find the .post method
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
The IDE (Webstorm) says that it can't find .post() method or function
Could you please help me ?
I'm using the last version of node.js.

Node.js express router.post returns 404 not found

My express application seems to return 404 NOT FOUND whenever im using a post request method in my routes file. GET-requests are working fine and i can only see "GET" requests in the console aswell, even if im using a post request.
Is there some missing link between app.js and routes/index.js that might be causing this?
// routes/index.js
router.post('/foo', function (req, res, next) {
res.setHeader('Content-Type', 'application/json');
res.send('You sent: sdadad to Express');
})
// App.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var app = express();
var cors = require('cors')
app.use(cors())
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Result:
Not Found 404
Error: Not Found
at C:\Users\willow\Desktop\backend\app.js:29:13
at Layer.handle [as handle_request] (C:\Users\willow\Desktop\backend\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\willow\Desktop\backend\node_modules\express\lib\router\index.js:317:13)
at C:\Users\willow\Desktop\backend\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\willow\Desktop\backend\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\willow\Desktop\backend\node_modules\express\lib\router\index.js:275:10)
at C:\Users\willow\Desktop\backend\node_modules\express\lib\router\index.js:635:15
at next (C:\Users\willow\Desktop\backend\node_modules\express\lib\router\index.js:260:14)
at Function.handle (C:\Users\willow\Desktop\backend\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\willow\Desktop\backend\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (C:\Users\willow\Desktop\backend\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\willow\Desktop\backend\node_modules\express\lib\router\index.js:317:13)
at C:\Users\willow\Desktop\backend\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\willow\Desktop\backend\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\willow\Desktop\backend\node_modules\express\lib\router\index.js:275:10)
at SendStream.error (C:\Users\willow\Desktop\backend\node_modules\serve-static\index.js:121:7)
What you wanna do should look like this in practice:
// routes/index.js
module.exports = (express) => {
// Create express Router
var router = express.Router();
// add routes
router.route('/foo')
.post((req, res) => {
res.setHeader('Content-Type', 'application/json');
res.send('You sent: sdadad to Express');
});
return router;
}
// App.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes')(express); // require routes at routes/index.js
var app = express();
var cors = require('cors')
app.use(cors())
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
What I usually do is create a function that expects express as param like this
(routes/index.js)
module.exports = (express) => {
// Create express Router
var api = express.Router();
// add routes
api.route('/some_endpoint')
.post((req, res) => {
res.json({ message : 'some message' })
});
return api;
}
then I just import this file to my app.js
like this
(app.js)
// set api as a middleware
const api = require('./routes')(express);
app.use('/api/v1', api);
that way I hook up my api and my server.

Why is req.body always undefined for me

I cannot access any request parameters. e.g. req.body.username. for some reason req.body is always undefined. The endpoint is /youtube
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
server.js
var express = require("express");
var mysql = require('mysql');
var app = express();
var pool = mysql.createPool({
connectionLimit : 100, //important
host : 'localhost',
user : 'user',
password : 'pass',
database : 'db',
debug : false
});
var router = express.Router();// get an instance of the express Router
// middleware to use for all requests
router.use(function(req, res, next) {
// do logging
console.log('Incoming request');
next(); // make sure we go to the next routes and don't stop here
});
app.get("/",function(req,res){-
handle_database(req,res);
});
router.route('/youtube')
.post(function(req, res) {
console.log(req.body); // always undefined
})
.get(function(req, res) {
});
app.use('/api', router);
app.listen(3000);
console.log("Listening on port 3000....")
Add those 3 lines right below var app = express(); in server.js:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
Now your req.body will not be undefined.

html 5 mode remove hash in angularjs+nodejs

i am new in mean stack i want to remove the hash in URL of the browser.i successfully do this but when i refresh the page at that time 'Network error 404 not found' comes so please help me to solve this problem.
below i show the code of index.html file.
<script>
var base = document.createElement('base');
base.href = 'http://localhost:3000/';
document.getElementsByTagName('head')[0].appendChild(base);
</script>
below is the code of the config.router.js
angular.module('app')
.config(
['$stateProvider', '$urlRouterProvider','$locationProvider', 'MODULE_CONFIG',
function ($stateProvider, $urlRouterProvider,$locationProvider, MODULE_CONFIG) {
$locationProvider.html5Mode(true).hashPrefix('!');
below is the code of the server.js file of the node.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var routes = require('./routes/index');
var country = require('./routes/country');
var category = require('./routes/Category');
var attributes = require('./routes/Attribute');
var subscription = require('./routes/subscription');
var mall = require('./routes/mall');
var http = require('http');
var user = require('./routes/user');
var app = express();
//var cors = require('cors');
// view engine setup
//app.use(cors());
app.set('views', path.join(__dirname, '../app'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true }));
app.use(bodyParser.json({limit: '50mb'}));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.use(cookieParser());
//app.use(bodyParser({limit: '50mb'}));
app.use(express.static(path.join(__dirname, '../app/')));
/*allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length');
next();
};
app.use(allowCrossDomain);*/
app.use(express.static(path.join(__dirname, '../app/')));
app.use('/', routes);
app.use('/api/user', user);
app.use('/api/country', country);
app.use('/api/city', country);
app.use('/api/state', country);
app.use('/api/mall', mall);
app.use('/api/category', category);
app.use('/api/attributes', attributes);
app.use('/api/subscription', subscription);
app.set('port',3000);
mongoose.connect('mongodb://52.39.244.83 /deals');
var db = mongoose.connection;
db.on('error',erroroccured);
db.once('open',startserver);
function erroroccured(){
console.log('error');
}
function startserver(){
// mongoose.set( "debug", true );
var server = app.listen(app.get('port'), function() {
console.log('Server listening on port ' + server.address().port);
});
}
module.exports = app;
so please help me to come out from this problem thanks to all in advance.
Because you have defined the hashPrefix('!') config, your URLs will now be
index.html#!/path
If you want a plain HTML5 mode style, like
index.html/path
Just don't define the hashPrefix. It defaults to ''.
Additionally you can also get rid of the base tag, but that might create issues with are going to define a base tag, define it as
<head>
<base href="/">
</head>
Instead of localhost:3000 as this would fail on your server.
I think just use this should be fine
$locationProvider.html5Mode(true);
And in html
<head>
<base href="/">
</head>

Handlebars Missing helper

I'm trying to implement my own helper for Handlerbars but i cannot figure out where i need to register it so I can access it inside my template.
I always get Missing helper: "abcde"
I've checked many of the same questions on here having the same issue but with no success.
Here's my app.js :
var express = require('express');
var handlebars = require('handlebars');
var expresshandlebars = require('express-handlebars');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', expresshandlebars({ defaultLayout: 'main', layoutsDir: path.join(__dirname, 'views/layouts') }));
app.set('view engine', 'handlebars');
handlebars.registerHelper('abcde',
function (str) {
return str;
}
);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '../../site')));
app.use('/', index);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Here's how i use the template inside my main.handlebars layout file:
{{abcde "test"}}
Did you try this technique? From here https://www.npmjs.com/package/express-handlebars
var express = require('express');
var exphbs = require('express-handlebars');
var app = express();
var hbs = exphbs.create({
// Specify helpers which are only registered on this instance.
helpers: {
foo: function () { return 'FOO!'; },
bar: function () { return 'BAR!'; }
}
});
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
Either way, I would focus on setting the helper on your expresshandlebars, and not your handlebars variable.

Categories

Resources