AJAX call to/from MongoDB example for Node/Express?

后端 未结 1 1746
粉色の甜心
粉色の甜心 2021-02-06 16:15

This is to start with a very basic page: HTML Form, a button, and a div-box.

.click of the button would POST the Form data through AJAX.

The data is to

相关标签:
1条回答
  • 2021-02-06 16:27

    Few suggestions

    Regarding the ajax call in index.html

    1. If your index.html is served by the same server, then please don't use a cross domain call. The url property in $.ajax could be a relative url like /start.
    2. Also you can think of not using jsonp request.

    the call could be like

    $.ajax({
        dataType: 'json',
        data: $('#formID').serialize(),
        type: 'POST',
        url: "./start",
        success: handleButtonResponse,
    });
    

    How/Where does the JSON connect to/from MongoDB?

    In you ajax call you are requesting for ./start, So the same route should be made in your express server. like

    app.get('/start', function (req, res) {    
        db.collection('collectionName').insert({req.data}, function (err, doc) {
               //rest of code 
        });    
    });
    

    does Express require a templating engine, such as Consolidate? If so, how/where does that fit in?

    You have many options for templating like jade,ejs,hbs and so on. If you use jade or any of them your html rendering code in express routes will get simplified.

    without a templating engine

    response.writeHead(200, {"Content-Type:": "application/json"}); 
    var submittedPost = {};
    submittedPost['message'] = 'Proof that Node and Mongo are working..';
    response.write( "_wrapper('" );
    response.write( JSON.stringify(submittedPost) );
    response.write( "')");              
    response.end();
    

    with a templating engine like jade (now pug)

    var submittedPost = {};
    submittedPost['message'] = 'Proof that Node and Mongo are working..';
    response.json(submittedPost);
    

    also with templating engines you can render templates with server side variables and you can access them inside your templates like

    app.get('/mypage', function (req, res) { 
        res.render('mytemplate_page',{template_variable:some_variable});
    });   
    

    and you can use template_variable inside the template for looping through or displaying.

    0 讨论(0)
提交回复
热议问题