Node js ajax post request

It except an error with Node js and AJAX POST, The Node request cannot check if form data are correctly handled, always it drop to error function, any solution to check below AJAX NODE JS CODE

$("#submit_btn").click(function() {
    $.ajax({
        url: '/process_add',
        type: 'POST',
        dataType: "json",
        data: $('#process_form').serializeArray(),
        success:function(data) {
            alert('done');
        },
        error: function(errorThrown,data) {
            alert('Error');
        }
    });
});


router.post('/process_add', function(req, res, next) {

    var item = {
        name: req.body.name,
        content:req.body.content
    };

    mongo.connect(url, function(err, db) {
        assert.equal(null, err);
        db.collection('data_collection').insertOne(item, function(err, result) {
            assert.equal(null, err);
            console.log('Process added');
            db.close();
        });
    });
});

Answers:

Answer

You need to add the ('/') root for that api to Ajax request .post has (/process_add) hints not root for that api so if index is root ('index/process_add)

Answer

Your AJAX request '/process_add' will point to the root of your URL.Say for example abc.com is your domain the endpoint here would be 'abc.com/process_add'. Ensure your router exists in the root reference of '/' in app.Something like this

app.js

var index = require('./routes/index');    
app.use('/',index);

routes/index.js

    router.post('/process_add', function(req, res, next) {

        var item = {
            name: req.body.name,
            content:req.body.content
        };

        mongo.connect(url, function(err, db) {
            assert.equal(null, err);
            db.collection('data_collection').insertOne(item, function(err, result) {
                assert.equal(null, err);
                console.log('Process added');
                db.close();
            });
        });
    });

Happy Coding!

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.