AJAX调用/从MongoDB的示例节点/ EX preSS?节点、示例、MongoDB、AJAX

2023-09-10 17:02:55 作者:爱你没商量

这是开始一个非常基本的网页:HTML表单,一个按钮,一个div盒的

按钮。点击将通过AJAX POST表单数据。

的数据是要被存储在MongoDB中,并检索到的div-盒无需页面刷新。

AJAX从index.html的:的

  $(文件)。就绪(函数()
{

    //手柄按钮点击
    $('#buttonID)。点击(函数(){

        //使一个Ajax调用
        $阿贾克斯({
            数据类型:JSONP,
            jsonpCallback:_wrapper,
            数据:$('#formID')序列化()。
            键入:POST,
            网址:HTTP://本地主机:9999 /启动,
            成功:handleButtonResponse,
            });
    });

    函数handleButtonResponse(数据)
    {
        //解析JSON字符串
        VAR的JSONObject = JSON.parse(数据);
        $('#reponseID)追加(jsonObject.message)。
    }

});
 

app.js:的

  VAR EX preSS =需要('EX preSS),
    应用= EX preSS();
    缺点=需要('巩固');
    MongoClient =需要('mongodb的')。MongoClient,
    服务器=需要('mongodb的)服务器。

app.engine(HTML,cons.swig);
app.set(视图引擎,HTML);
app.set('意见',__dirname +/意见);

VAR mongoclient =新MongoClient(新服务器(本地主机,27017,
                                                {'native_parser:真}));

变种DB = mongoclient.db('数据库名称');

app.get('/',功能(REQ,RES){

    db.collection(集合名)。找到({},功能(ERR,DOC){
            res.render(索引,DOC);
    });

    response.writeHead(200,{内容类型::应用/ JSON});
    变种submittedPost = {};
    submittedPost ['消息'] ='证明节点和蒙戈的工作..;
    回复于(_wrapper();
    回复于(JSON.stringify(submittedPost));
    回复于('));
    到Response.End();

});

app.get('*',功能(REQ,RES){
    res.send(404 ......,404);
});

mongoclient.open(功能(ERR,mongoclient){

    如果(ERR)抛出ERR

    app.listen(9999);
    的console.log(前preSS启动服务器端口号为9999);
});
 

如何/在什么地方JSON连接到/从MongoDB的?

此外,没有防爆preSS需要一个模板引擎,比如整合?如果是这样,如何​​/在哪里这是否合适吗?

解决方案

的几点建议

关于中的index.html

Ajax调用 如果你的 index.html的由服务在同一台服务器,那么请不要使用跨域调用。该网​​址属性 $。阿贾克斯可能是一个相对URL如 /启动。 你也可以考虑不使用 JSONP 请求。

通话也能像

  $。阿贾克斯({
    数据类型:JSON,
    数据:$('#formID')序列化()。
    键入:POST,
    网址:./start
    成功:handleButtonResponse,
});
 
使用Express和MongoDB构建Serverless API的速成课程

如何/在什么地方JSON连接到/从MongoDB的?

在你的AJAX调用您要查询有关 ./启动,所以同样的路线应该在你的前preSS服务器进行。像

  app.get('/启动'功能(REQ,RES){
    db.collection(集合名)。插入({req.data},功能(ERR,DOC){
           //将code休息
    });
});
 

不防爆preSS需要一个模板引擎,比如整合?如果是这样,如何​​/在哪里这是否合适吗?

您有很多选择的模板如玉,EJS,哈佛商学院等。 如果您使用的玉或其中任何你的HTML渲染code的前preSS航线将得到简化。

没有模板引擎

  response.writeHead(200,{内容类型::应用/ JSON});
变种submittedPost = {};
submittedPost ['消息'] ='证明节点和蒙戈的工作..;
回复于(_wrapper();
回复于(JSON.stringify(submittedPost));
回复于('));
到Response.End();
 

与emplating引擎如玉

  VAR submittedPost = {};
submittedPost ['消息'] ='证明节点和蒙戈的工作..;
response.json(submittedPost);
 

也与模板引擎可以渲染服务器端变量的模板,你可以访问他们你的模板里面像

  app.get('/我的空间,​​功能(REQ,RES){
    res.render('mytemplate_page',{template_variable:some_variable});
});
 

您可以使用 template_variable 在模板中进行遍历或显示。

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 be stored in MongoDB, and retrieved into the div-box without a page-refresh.

AJAX from index.html:

$(document).ready(function()
{   

    // handle button clicks         
    $('#buttonID').click(function() {

        // make an ajax call
        $.ajax({
            dataType: 'jsonp',
            jsonpCallback: '_wrapper',
            data: $('#formID').serialize(),
            type: 'POST',
            url: "http://localhost:9999/start",
            success: handleButtonResponse,
            });
    });

    function handleButtonResponse(data)
    {
        // parse the json string
        var jsonObject = JSON.parse(data);
        $('#reponseID').append( jsonObject.message );
    }

});

app.js:

var express = require('express'),
    app = express();
    cons = require('consolidate');
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server;

app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname + "/views");

var mongoclient = new MongoClient(new Server('localhost', 27017,
                                                { 'native_parser' : true }));

var db = mongoclient.db('database_name');

app.get('/', function (req, res) {

    db.collection('collectionName').find({}, function (err, doc) {
            res.render('index', doc);   
    });

    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();

});

app.get('*', function (req, res) {
    res.send("404..", 404);
});

mongoclient.open(function (err, mongoclient) {

    if (err) throw err

    app.listen(9999);
    console.log("Express server started on port 9999");
});

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

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

解决方案

Few suggestions

Regarding the ajax call in index.html

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. 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 emplating engine like jade

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.