NodeJS URL 路由和渲染 HTML



我是nodejs编程的新手,我现在遇到了一个小问题。当我尝试去本地主机:3000/我想回家控制器和索引函数打印HTML文件时。

应用.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!'))

主控制器

.JS
var path    = require("path");
exports.index = function(req, res){
  res.sendFile(path.join(__dirname+'/index.html'));
};
console.log('test33');

此外,我正在使用导出来将应用程序与其他控制器分开.js。这是正确的方法吗?我有Python Django框架的历史,我们曾经使用URL来导航我们的程序。

谢谢。

输出

无法获取 /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);

您的homeController.js导出一个index函数,该函数需要两个参数reqres。因此,您必须相应地更新您的应用程序.js:

app.get('/', function(req, res) {
  homeController.index(req, res);
});

编辑:顺便说一下,您的应用程序正在侦听端口 3000

最新更新