[英]Cannot Get/ in node.js
我正在关注此http://www.expertphp.in/article/user-login-and-registration-using-nodejs-and-mysql-with-example链接
我得到一个不能GET /错误,我已经尝试了所有的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'))
有用的链接:
你有两种方式:
1)阅读index.html
内容并在root url上提供:
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);
优点缺点:
1-ST例子仅仅是阅读的index.html 一次 变量 ,将服务的内容,但需要重新启动应用程序重新读取该文件。
第二个例子是在views
文件夹中使用.html
文件作为ejs
文件,这提供了将变量传递给html文件的机会 ,这比仅仅发送文件更好 ,+你可以使用<% include partials/header.ejs %>
在另一个中包含一个html <% include partials/header.ejs %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.