lrony* 2014-10-21 14:55 采纳率: 0%
浏览 274

Express Node JS 404错误

I am struggling with a 404 error when I attempt to post an ajax request using the below code"

// Use AJAX to post the object to our addReport service
    $.ajax({
        type: 'POST',
        data: newReport,
        url: '/add/addreport',
        dataType: 'JSON'
    })

My app.js contains the routes

var routes = require('./routes/index');
var reports = require('./routes/reports');
var add = require('./routes/add');

and

app.use('/', routes);
app.use('/reports', reports);
app.use('/add', add);

and then in the route file I have

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

/*
 * GET reportList.
 */
router.get('/reportlist', function(req, res) {
    var db = req.db;
    db.collection('reports').find().toArray(function (err, items) {
        res.json(items);
    });
});


/*
 * POST to addreport
 */
router.get('/addreport', function(req, res) {
    var db = req.db;
    db.collection('reports').insert(req.body, function(err, result){
        res.send(
            (err === null) ? { msg: '' } : { msg: err }
        );
    });
});

module.exports = router;

The GET request works fine. But I get a 404 on the POST (addreport).

I think I have all the necessary parts but I am new to express. Perhaps I am missing something?

  • 写回答

1条回答 默认 最新

  • weixin_33730836 2014-10-21 14:59
    关注

    you should change your method on the route you are using get as well for 'addreport'

    try to change it to post like this:

    router.post('/addreport', function(req, res) {
        var db = req.db;
        db.collection('reports').insert(req.body, function(err, result){
            res.send(
                (err === null) ? { msg: '' } : { msg: err }
            );
        });
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置