Node JS res.sendFile() not working

做~自己de王妃 提交于 2020-01-05 07:18:35

问题


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

回答1:


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




回答2:


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; 



回答3:


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


来源:https://stackoverflow.com/questions/47665797/node-js-res-sendfile-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!