0

Using nodeJs,ExpressJS(~4)

This is my structure:

controllers/searchController.js
public/javascripts/search.js (js client code that will run on browser)
public/search.html
server.js
app.js

searchController.js:

var express = require('express');
var router = express.Router();
var esService = require('../services/esService');
var Q = require('q');



var html_dir = './public/';
router.get("/home", function (req, res) {
    res.sendfile(html_dir + 'search.html');
})

router.get("/search", function (req, res) {
 ...
})

module.exports = router;

app.js:

var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var searchController = require('./controllers/searchController');    
var app = express();

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

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(__dirname, '/public'));

app.use('/', searchController);

/// 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;

search.html:

<!DOCTYPE html>
<html>
<head>
....
</head>
<body>
 ........

<div id="tfheader">
    <form id="tfnewsearch" method="get" onsubmit="return handleClick()">
        <input id="myinput" type="text" class="tftextinput" name="q" size="21" maxlength="120">
        <input type="submit" value="search" class="tfbutton">
    </form>
    <div class="tfclear"></div>
</div>



<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="javascripts/prettyprint.js"></script>
<script src="javascripts/search.js"></script>


...
</body>
</html>

and this is search.js:

function handleClick() {
    var inputParam = document.querySelector("#myinput").value;

    $.get('search?termToSearch=' + inputParam, function (responseText) {
        console.log(responseText);
        $("#resultlist").empty().append(prettyPrint(responseText));


    });

    return false;

}

Now when I acesss to: http://localhost:3000/home I am getting the folloing error on the browser:

Remote Address:127.0.0.1:3000
Request URL:http://localhost:3000/javascripts/search.js
Request Method:GET
Status Code:404 Not Found

Remote Address:127.0.0.1:3000
Request URL:http://localhost:3000/javascripts/prettyprint.js
Request Method:GET
Status Code:404 Not Found

Any idea why?

rayman
  • 20,786
  • 45
  • 148
  • 246

1 Answers1

1

You should change

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

to:

app.use(express.static(__dirname + '/public'));

But if you really want to fix this problem it's better to use an prefix for static file like this:

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

and then load your Javascript files in this way:

<script src="public/javascripts/prettyprint.js"></script>
<script src="public/javascripts/search.js"></script>
Alireza Ahmadi
  • 1,541
  • 18
  • 22
  • That worked. but please explain me how you solved it that way? and what do you think about my structure? where should I put my html's files – rayman Jul 28 '14 at 10:31
  • You was passed `__dirname` and `/public` as separate arguments to the `express.static` middleware, While this middleware only accepts one arguments. So I have changed `,` to `+`. And in a more standard way you should pass `path.resolve(__dirname, 'public')` to this middleware. – Alireza Ahmadi Jul 28 '14 at 10:38
  • And about your project structure I can simply say that's a normal structure, But if you want to make your project structure better, read [this question](http://stackoverflow.com/questions/5178334/folder-structure-for-a-nodejs-project) – Alireza Ahmadi Jul 28 '14 at 10:41
  • What about my overall structure? would you fix that? – rayman Jul 28 '14 at 10:41
  • @rayman Also if you start using Yeoman and specially [this generator](https://github.com/petecoop/generator-express) your code would get more organized. – Alireza Ahmadi Jul 28 '14 at 10:45