我是 Nodejs 编程新手,现在遇到了一些问题。当我尝试访问 localhost:3000/时,我想访问 homeController,索引函数会打印 HTML 文件。
APP.JS
const express = require('express')
const mongoose = require('mongoose')
const mongodb = require('mongodb')
const app = express();
const homeController = require('./home/homeController.js');
app.get('/', function(req, res) {
res.redirect(homeController.index);
});
app.listen(3000, () => console.log('Example app listening on port 80!'))
HOMECONTROLLER.JS
var path = require("path");
exports.index = function(req, res){
res.sendFile(path.join(__dirname+'/index.html'));
};
console.log('test33');
我还使用导出将 app.js 与其他 Controller 分开。这是正确的方法吗?我有使用 Python Django 框架的历史,我们过去常常使用 URL 来导航我们的程序。
谢谢。
输出
Cannot GET /function%20(req,%20res)%7B%0A%20%20res.sendFile(path.join(__dirname+'/index.html'));%0A%7D
最佳答案
您的问题是 homeController.index
是一个函数,但您没有调用它。替换:
app.get('/', function(req, res) {
res.redirect(homeController.index);
});
与:
app.get('/', homeController.index);
关于javascript - NodeJS URL 路由和渲染 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49074205/