-1

As my question in Order of router precedence in express.js. I know that the order of express.js is first come first serve. But as code bellows, I don't understand that why the '__dirname' has declared and fixed in above of other code but whaterver I call javascript from ./public/abc.js, the app return a HTML markup of mainpage. My pages include some javascript and it cannot be loaded. The server return 100% HTML

I am using express generator and folders is structured follows.

NodeJS

var routes = require('./routes/index');
var api = require('./routes/api');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(__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('/api', api);
app.use('/users', users);

app.use('/:shopName', function(req, res, next) {
    req.shopName = req.params.shopName;
    next();
}, routes);

app.use('/', function(req, res) {
    res.render('index', {
        title: 'MainPage'
    });
});

Client Javascript put in script tags like

<script type="text/javascript" src='./public/javascripts/Crypto/crytoUtils.js'></script>

The browser send out error "Uncaught SyntaxError: Unexpected token < cryptoUtils.js " in console and when I click in a link, I see the mainpage HTML markup..

Help me solve the problem ... pls. Thank

Community
  • 1
  • 1
hoanganh17b
  • 867
  • 1
  • 11
  • 25

1 Answers1

1

The path to the js file should be ./abc.js, public is left out unless you set that as the root for static files using:

app.use('/public', express.static(path.join(__dirname, 'public')));

To be clear, I suggest NOT using the above code, and instead modify your url in the script tag src attribute to appropriately target the file at it's location of /javascripts/Crypto/crytoUtils.js

Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • Then the path you are using is still incorrect. This is a very simple problem, you simply need to use the correct path, the same path that you would use to get to that file in your browser. This isn't a code issue or a programming problem. Just the wrong url. – Kevin B Sep 16 '15 at 16:22