【问题标题】:NodeJS URL Routing and Render HTMLNodeJS URL 路由和渲染 HTML
【发布时间】:2018-03-03 01:48:00
【问题描述】:

我是 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 与其他控制器分开。这是正确的方法吗?我有使用 Python Django 框架的历史,我们曾经使用 URL 来导航我们的程序。

谢谢。

输出

无法获取 /function%20(req,%20res)%7B%0A%20%20res.sendFile(path.join(__dirname+'/index.html'));%0A%7D

【问题讨论】:

    标签: javascript node.js express


    【解决方案1】:

    您的问题是 homeController.index 是一个函数,但您没有调用它。替换:

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

    与:

    app.get('/', homeController.index);
    

    【讨论】:

      【解决方案2】:

      您的homeController.js 导出一个index 函数,该函数需要两个参数reqres。 所以你必须相应地更新你的 app.js :

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

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

      【讨论】:

        猜你喜欢
        • 2019-12-05
        • 1970-01-01
        • 2015-09-24
        • 2019-04-25
        • 2021-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多