Reputation: 540
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?
Upvotes: 0
Views: 205
Reputation: 16066
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 }
);
});
});
Upvotes: 2