如何将JSON数据从客户端发送到node.js服务器。

时间:2015-01-30 18:36:45

标签: javascript json node.js mongodb express

这是 server.js

var express = require("express"),
    http = require("http"),
    mongoose = require( "mongoose" ),
    app = express();

app.use(express.static(__dirname + "/client"));
app.use(express.urlencoded());

mongoose.connect('mongodb://localhost/PvdEnroll', function(err) {
  if (err) {
    console.log(err);
  } else {
    console.log('Connected to mongodb!');
  }
});

var CheckBoxSchema = mongoose.Schema({
    npi: String,
    boxes:[ String]
});

var CheckBox = mongoose.model("CheckBox", CheckBoxSchema);
http.createServer(app).listen(3000);

// here's where we get something from the client.
app.get("/checkbox.json", function (req, res) {
    CheckBox.find( {}, function(err, CheckBox) {
        console.log("STUBB2", checkbox);
        res.json(checkbox); 
    });
});

app.post("/checkbox", function (req, res) 
console.log("POSTING TO DB: ",req.body);

var newCkBoxData = new npiChecks({"npi": req.body.npi, "boxes":req.boxes});                 
    newCkBOxData.save(function(err, results) {
        if (err !== null) {
            console.log(err);
            res.send("ERROR");
        } else {
            CheckBox.find({}, function(err, result) {
                if (err !== null) {
                    // the element dir not get saved
                    res.send("ERROR");
                }
                res.json(result);
            });
        }
    });                                                       
});

客户端 secA.js,与单个HTML页面有关。

var main = function (checkBoxObjects) {
    "use strict";

    $.getJSON("../data/checkBoxesA.json", function(checkBoxTxt) {
        checkBoxTxt.forEach(function (data) {
            $(".checkbox-input").append("<input type='checkbox' unchecked/>");
            $(".checkbox-input").append(' ' + data.label + "<br/>");
            $(".checkbox-input").append(' ' + data.note +  "<br/>");
            $(".checkbox-input").append('              '+  "<br/>");
        });
   });
};
$(document).ready(main);

providerNPI_ckBs = [];
NPI_number = [];

var loopForm = function(form) {
    for ( var i = 0; i < form.elements.length; i++) {
        if (form.elements[i].type == 'checkbox')
            if (form.elements[i].checked == true) {
                providerNPI_ckBs += 1 + ' ';
            } else {
                providerNPI_ckBs += 0 + ' ';
            }
    }
    if (providerNPI_ckBs.length > 0) 
        if (NPI_number.length > 0) 
           createJSONobj(); 
}

var getNPI = function() {
    NPI_number = document.getElementById("text_field1").value;
        if (NPI_number.length > 0)
            if (providerNPI_ckBs.length > 0) {
               createJSONobj(); 
            }
}

var createJSONobj = function() {
    var JSONobj = '{' + JSON.stringify(NPI_number) + ':' + 
                   JSON.stringify(providerNPI_ckBs) + '}';
    JSON.stringify(JSONobj);
    console.log(JSONobj);

    // here we'll do a quick post to our todos route
    $.post("npi_checks", JSONobj, function (response) {
        console.log("We posted and the server responded!");
        console.log(response);
    });
}

// Note: This is temporary as I'm only intending to sent JSON data one way
// to the server. I'd just like to verify that I can send data both ways
$(document).ready(function (checkBoxObjects) {
    $.getJSON("checkbox.json", function (checkBoxObjects) {
        console.log("Client Recieved Array from Server: ", checkBoxObjects);
        main(checkBoxObjects);
    });
});

Chrome控制台会立即响应GET http://127.0.0.1:3000/html/checkbox.json 404(未找到)

页面加载并接受 secA.js 脚本格式化为JSON的数据。数据库已由服务器启动。我需要知道的是如何将数据发送到服务器!

我对javascript很新,生成这个应用程序是与MongoDB一起学习语言的一部分。我已经将这个应用程序结构化为一个示例教程。一个区别是,在本教程中,流量是客户端和服务器之间的两种方式。

感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

如果 post 的第一个参数在客户端更改为&#34;&#34; npi_checks&#34;到&#34; /复选框&#34;匹配第一个参数 app.post ,数据到达服务器并加载到mongoldb。这是一个简单的解决方案。