【问题标题】:Routes issue in Express 4Express 4 中的路线问题
【发布时间】:2015-04-18 21:37:32
【问题描述】:

Noob - 尝试使用 Express4 和 Node 上的路由设置 CRUD。我的以下 GET 和 POST 路由工作正常,但 DELETE 和 PUT 给出 404,未找到错误,这很奇怪。

我正在使用 Postman for Chrome 并将 Content Type 设置为 application/json,这一切正常 - 我注意到在 DELETE 和 PUT 查询中,标题仍然指出它是以 text/html 发送的,而不是比 JSON,尽管我将 RAW 设置都设置为 JSON,并将 Headers 内容类型手动设置为 application/json。

var express = require('express');
var router = express.Router();

var mongoose = require('mongoose');
var Todo = require('../models/Todo.js');

/* GET /todos listing. THIS IS WORKING*/
router.get('/', function(req, res, next) {
  Todo.find(function (err, todos) {
    if (err) return next(err);
    res.json(todos);
  });
});

/* POST /todos listings THIS IS WORKING*/
  router.post('/', function(req, res, next){
Todo.create(req.body, function(err, post){
    if (err) return next(err);
    res.json(post);
    });
});

/* GET /todos/id THIS IS WORKING*/
router.get('/:id', function(req, res, next) {
  Todo.findById(req.params.id, function (err, post) {
    if (err) return next(err);
    res.json(post);
  });
});

/* DELETE /todos/:id  NOT WORKING*/
router.delete('/:id', function(req, res, next) {
    console.log(req);
  Todo.findByIdAndRemove(req.params.id, req.body, function (err, post) {
    if (err) return next(err);
    res.json(post);
  });
});

module.exports = router;

这也是一个正在导入 app.js 的 routes.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 todos = require('./routes/todos');

// set our port
var port = process.env.PORT || 3000; 


//Requires the mongoose connection 
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/todoApp', function(err) {
    if(err) {
        console.log('connection error', err);
    } else {
        console.log('connection successful');
    }
});

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(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/todos', todos);


// 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: {}
    });
});



// start app ===============================================
// startup our app at http://localhost:3080
app.listen(port);               

// shoutout to the user                     
console.log('Magic happens on port ' + port);

module.exports = app;

【问题讨论】:

  • 请发布您的 app.js,以便获得帮助
  • app.js 在上面发布-感谢任何帮助-谢谢
  • 你能从 POSTMan 或你可以用来删除的工具中发布图片吗?

标签: javascript node.js rest express routes


【解决方案1】:

您可能需要检查几件事。

您的 POST 正在按预期工作,但您的 DELETE 和 PUT 却没有。您已将内容类型设置为 application/json。

鉴于您使用的是 Express 4,并且必须自己包含一个正文解析器,您是否恰好包含以下行?

var app = express();
// you probably have this, for application/x-www-form-urlencoded
app.use(bodyParser.urlencoded());

// extrapolating here, you only mentioned you were receiving 404s.
// you might be missing the following line?
app.use(bodyParser.json());

在您的删除路线中,您记录了响应对象,这是一个错字吗?一个更有用的日志将是请求对象 - 这样您就可以确定您认为您发送的路线究竟是什么。

在黑暗中拍摄,但在没有额外信息的情况下,我希望至少有一个答案是正确的。

【讨论】:

  • 嘿伙计 - 谢谢你 - 我包含了 bodyParser.json - 日志是一个工件,来自调试 - 但 console.log(req) 不会向控制台输出任何内容,这表明请求甚至没有通过路由。
  • @Mobaz 在您的删除中您有 console.log(res) 即根据您的评论响应而不是请求。
  • Mreh,没有更多信息可以继续,这很难调试。您能否至少写出您为此资源声明的所有方法(GET/POST/DELETE 等)的第一行?
  • 我不想问这些问题,但你是不是在打电话:DELETE localhost:1337/todos/3 强调删除和 id 3,这是邮递员实际发送的内容吗? (对不起,如果你已经这样做了)
  • Irysius - 这是我愚蠢的答案,没有在 URI 字符串中添加我需要 PUT 的 id - 这意味着服务器不知道该怎么做 - 这很痛苦,但是我学到了很多关于节点快速路由和 REST 的知识! - 感谢您的贡献
【解决方案2】:

我查看了您的实现,看起来不错。我觉得它可能出错的一个机会是,如果我们查看Model.findOneAndRemove(conditions, [options], [callback]) 的文档,你会在[options] 中出错。

在 [options] 中我们可以这样做:

  • 排序:如果条件找到多个文档,则设置排序 顺序选择要更新的文档
  • 选择:设置要返回的文档字段

试试这个,我希望它能解决你的问题。 您提到,PUT 也有相同的 404 问题,请您更新您的帖子,包括相同的问题。让我们了解哪里出错了。

【讨论】:

  • 感谢这一点 - 但请求甚至没有从 router.put(..) 中记录 - 在它通过 Model.findOneAndRemove() 运行之前
  • 我可以知道您是如何从您的视图页面调用它的吗?
  • 使用jade调用视图
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-10
  • 1970-01-01
  • 2016-06-11
  • 1970-01-01
  • 1970-01-01
  • 2015-07-13
  • 2019-09-02
相关资源
最近更新 更多