【发布时间】:2018-05-09 11:10:44
【问题描述】:
我有一个带有 /request 路由的页面,其中包含一个表单。表单方法是 POST,动作是 /request。 request.js 中的 POST 处理程序中应该发生的事情是对表单数据进行处理(存储在 DB 等中),然后使用路由 /trips。
每当我使用 res.send("Some text here"); 时,GET 处理程序都可以正常工作但是当我尝试使用 res.render('trips') 渲染页面时,给我一个 HTTP 500 内部服务器错误。
这是 request.js 的代码:
var router = require('express').Router();
router.get('/', checkLoggedIn, function (req, res) {
res.render('request', {
user: req.user // get the user out of session and pass to template
});
});
router.post('/', checkLoggedIn, function (req, res) {
console.log(req.body); //data should be stored in DB
res.redirect('/trips'); //Should redirect to /trips after form
submission. Why ERROR 500?
});
function checkLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
//Redirect to home if not logged in
res.redirect('/');
}
module.exports = router;
这是 trips.js 的代码:
var router = require('express').Router();
router.get('/', checkLoggedIn, function(req, res) {
res.send("This is the trips route GET response!");
});
所以 上面的部分工作 并打印 “这是旅行路线 GET 响应!” 当我访问 localhost:8000/trips(从导航栏或通过提交表格)
router.get('/', checkLoggedIn, function(req, res) {
res.render('trips');
});
但是,当我写这篇文章时,它给了我一个 HTTP ERROR 500 localhost 当前无法处理这个请求。
function checkLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
//Redirect to home if not logged in
res.redirect('/');
}
module.exports = router;
这是我的 trips.ejs 文件(用于上下文):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!--<title><%= user.firstName %>'s Trips - Erkab</title>-->
<!--<meta name="viewport" content="width=device-width, initial-scale=1">-->
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0"/>
<meta name="apple-mobile-web-app-capable" content="yes"/>
<link rel="stylesheet" href="/public/css/base.css">
<link rel="stylesheet" href="/public/css/main.css">
<link rel="stylesheet" href="/public/css/erkab.css">
<script src="/public/js/modernizr.js"></script>
</head>
<body id="top" style="width: 100%">
<% include templates/header.ejs %>
<% if (userType != "Rider") {
userType = "Driver";
} %>
<div id="changeableView" class="container-fluid">
<table class="table table-hover">
<thead class="thead-inverse">
<tr>
<th>#</th>
<th>USER TYPE</th>
<th>LOCATION</th>
<th>DATE</th>
<th>TIME</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td><%= userType %></td>
<td><%= points %> - <%= area %></td>
<td><%= date %></td>
<td><%= time %></td>
</tr>
</tbody>
</table>
</div>
<script src="/public/js/jquery-2.1.3.min.js"></script>
<script src="/public/js/main.js"></script>
</body>
</html>
【问题讨论】:
-
您在 Node 控制台中看到了什么错误?这可能就像 EJS 文件尝试使用您未传入的变量一样简单。您可以尝试将该文件的内容更改为“Hello”之类的内容,以查看是否成功呈现。如果没有,也许您可以发布您用于配置设置
views和view engine的代码,以便我们再次检查您是否正确设置了这些设置? -
你好像问了两次同样的问题stackoverflow.com/questions/47486074/…
标签: javascript node.js http express server