Prashant Bhardwaj
Prashant Bhardwaj

Reputation: 86

Node JS res.sendFile() not working

I'm getting ReferenceError: main is not defined when I open up the http://localhost:3000/

Here I try to open up the main.html located in views directory

This is my app.js

const express = require('express'),
  app = express(),
  config = require('./config/index'),
  routes = require('./routes/route');

app.use(express.static(`${__dirname}/public`));
app.use(express.static(`${__dirname}/views`));
app.use('/',routes);
app.listen(config.port,()=>{
console.log(`Listing at port ${config.port}`)})

This is my route.js

const express = require('express'),
router = express.Router(),
helpers = require('../helpers/index');

router.route('/')
.get(helpers.index)

module.exports = router

This is my helpers/index.js

var user = require('../user/user');

exports.index = (req,res)=>{
    if(user.name == ''){
        res.sendFile(main.html);
    }
    else{    
        res.sendFile(chat.html)
    }
}

module.exports = exports;   

Directory Structure

>helpers
  >index.js
>routes
  >route.js
>user
  >user.js
>views
  >main.html
  >chat.html
app.js
pacakage.json

Upvotes: 2

Views: 16449

Answers (3)

jfriend00
jfriend00

Reputation: 707148

Change:

res.sendFile(main.html);

to:

res.sendFile("main.html");

Without the quotes, it's trying to interpret main as a Javascript object which it looks for the .html property on. But, there is apparently no object named main so you get ReferenceError: main is not defined. You want to pass a string here instead.

Same for res.sendFile("chat.html");


If the files are not local to this module's directory, then you need to build a more complete path that specifies their location. Given the file hierarchy you show, I think that might be something like this:

const path = require('path');
const options = {root: path.join(__dirname, "../views")};

res.sendFile("main.html", options);

Upvotes: 4

Sandip Ghosh
Sandip Ghosh

Reputation: 719

In addition to jfriend00's answer, you must also, build the correct absolute path, using the global __dirname variable in node.

So your path will be something like: res.sendFile(__dirname + "/main.html") or, depending on your folder structure: res.sendFile(__dirname + "/someadditionalfoldrs/main.html")

or, construct the path using "./" if applicable, like "./main.html";

Upvotes: 2

ufxmeng
ufxmeng

Reputation: 2600

var user = require('../user/user');
var path = require('path');

exports.index = (req,res)=>{
    if(user.name == ''){
        res.sendFile(path.resolve('views/main.html'));
    }
    else{    
        res.sendFile(path.resolve('views/chat.html'))
    }
}

module.exports = exports; 

Upvotes: 3

Related Questions