简体   繁体   中英

Issue with rendering view page in node express.js application

I am trying to render a static HTML page located in the views directory but when I try to visit that route, the Node.js console firing an error.

Error message

TypeError: path must be absolute or specify root to res.sendFile
    at ServerResponse.sendFile (C:\Users\Administrator\Desktop\node-mvc-setup\node_modules\express\lib\response.js:425:11)
    at C:\Users\Administrator\Desktop\node-mvc-setup\app.js:21:7
    at Layer.handle [as handle_request] (C:\Users\Administrator\Desktop\node-mvc-setup\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\Administrator\Desktop\node-mvc-setup\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\Administrator\Desktop\node-mvc-setup\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\Administrator\Desktop\node-mvc-setup\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\Administrator\Desktop\node-mvc-setup\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Users\Administrator\Desktop\node-mvc-setup\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\Administrator\Desktop\node-mvc-setup\node_modules\express\lib\router\index.js:275:10)
    at urlencodedParser (C:\Users\Administrator\Desktop\node-mvc-setup\node_modules\body-parser\lib\types\urlencoded.js:91:7)

Index.html

 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Test Node MVC Front Page</title> </head> <body> <h1>Great index font page</h1> </body> </html>

Index route

const express = require("express");

//require the express router

const router = express.Router();

router.get("/", function(req, res, next) {
  res.sendFile("/views/index.html");
});

module.exports = router;

项目结构图

Can you require path module in your code and try doing this instead:


router.get("/", function(req, res, next) {
    res.sendFile(path.join(__dirname, '../views', 'index.html'));
});

//require path

const path = require('path');

//require express const express = require("express");

//require express router

const router = express.Router();

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

  res.sendFile(path.join(__dirname, '../', 'views', 'index.html'));

});

module.exports = router

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM