【发布时间】:2015-12-23 19:34:02
【问题描述】:
对于想要学习新脚本或语言的人来说,我的问题与其说是生产代码,不如说是官方文档的问题。
安装 express-generator (0.12.2) 和 express (4.13.1) 后,我可以通过运行以下命令成功创建一个新项目以下命令:
npm express example
example 目录现在在我的驱动器上,然后我更改目录并安装 package.JSON 文件中的所有默认依赖项:
cd example && npm install
目前没有问题。
我打开位于“example”目录根目录下的 app.js 文件,Express 4 版本的 app.js 如下:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.listen(3000)
module.exports = app;
在添加 app.listen(3000); 行(倒数第二行)作为从上一个线程 (Starting Express.js Using app.js or 'npm start'?) 中学到的之后,运行以下命令允许我为 示例目录:
node app.js
一切都好。但是,在访问 Express 文档后,也适用于版本 4 (http://expressjs.com/guide/routing.html),我看到以下说明:
路由路径路由路径,结合请求方法,定义 可以向其发出请求的端点。它们可以是字符串, 字符串模式或正则表达式。 基于字符串的路由路径示例:
// will match request to the root
app.get('/', function (req, res) {
res.send('root');
});
// will match requests to /about
app.get('/about', function (req, res) {
res.send('about');
});
// will match request to /random.text
app.get('/random.text', function (req, res) {
res.send('random.text');
});
在 Express 4 文档中添加以下行后:
// will match requests to /about
app.get('/about', function (req, res) {
res.send('about');
});
并访问以下网址:
http://127.0.0.1:3000/about
我收到 404 not found 错误,以及第 30 行的错误,即:
28 // application routes
29 app.post('/', function(req, res, next) {
30 res.send(req.body);
31 });
有什么想法吗?
【问题讨论】:
-
您在代码中的什么位置放置了/关于路由?
-
@ezrepotein ,我将代码放在“app.use”路由命令之后和 404 分配之前。这似乎是放置它们的合乎逻辑的地方。但是,既然您问了这个特定的问题,也许我会尝试将它们放在代码的不同部分。也许我在代码中分配的路线太晚或太早了?
-
@ezrepotein,我已经找到了我的主要问题。我用于教程的书是一本很棒的书,但是用于教程和下载代码的 Express 版本是 3.12.0。所以,我注意到大量的脚本、路由和方法是相似的,但编码不同。如果我并排查看每个 app.js,就会发现一些明显的差异会导致错误。我将只使用 Express 3.12.0,直到我完成本书的原则。