无法获取/ in node.js



我遵循此http://www.expertphp.in/article/user-login-and-registration-using-nodejs-and-nodejs-and-mysql-with-with-example lemn>

我得到一个无法获得/错误,我尝试了所有stackoverflow答案,但没有解决。

var express=require("express");
var bodyParser=require('body-parser');
var app = express();
var authenticateController=require('./controllers/authenticate-controller');
var registerController=require('./controllers/register-controller');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
/* route to handle login and registration */
app.get('/', function (req, res) {
    res.render('index', {});
  });
app.post('/api/register',registerController.register);
app.post('/api/authenticate',authenticateController.authenticate);
app.listen(8012);

这是我当前的代码

据我了解,

您正在尝试以路径/发送index.html。那很好,但是不要使用render。只需发送index.html这样:

// replace this
app.get('/', function (req, res) {
  res.render('index', {});
});
// by this
app.get('/', (req, res) => res.sendFile('full/path/to/index.html'))

有用的链接:

  • res.render上的Express Doc
  • res.sendfile的Express Doc

您有2种方法:

1)读取index.html内容并在根网址上使用:

const fs = require('fs');
const indexFileContent = fs.readFileSync('path/to/index.html'); // caching file content to variable, to avoid re-reading it
app.get('/', (req, res) => {
  res.send(indexFileContent);
});

2)将 ejs定义为 .html文件渲染器:

const path = require('path');
const bodyParser = require('body-parser');
const express = require("express");
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine','ejs'); // make sure You've installed ejs:  npm i --save ejs
app.engine('ejs', require('ejs').renderFile);
app.engine('html', require('ejs').renderFile); // defining html renderer engine
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

app.get('/', (req, res) => res.render('index'));

// API controllers
const AuthController = require('./controllers/authenticate-controller');
const RegistrationController = require('./controllers/register-controller');
// API endpoints
app.post('/api/authenticate', AuthController.authenticate);
app.post('/api/register', RegistrationController.register);
app.listen(8012);

pros-cons:

1-ST 示例将简单地 index.html 一次但是Will 需要重新启动应用程序重新阅读该文件。

2-nd 示例示例是在views文件夹中使用.html文件作为ejs文件,该文件给出了机会传递 variables to html文件更好的简单地发送文件, 您可以使用<% include partials/header.ejs %>

在另一个HTML中包含一个HTML

最新更新