Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get base path from Node js Side?

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;
like image 410
Sumit patel Avatar asked Oct 30 '22 14:10

Sumit patel


1 Answers

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
like image 173
ricky Avatar answered Nov 15 '22 06:11

ricky