简体   繁体   中英

How to send JSON data from client to node.js server.

Here is 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);
            });
        }
    });                                                       
});

The client, secA.js, pertains to a single HTML page.

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

The Chrome console responds immediately with GET http://127.0.0.1:3000/html/checkbox.json 404 (Not Found)

The page loads and will accept data which the secA.js script formats as JSON. The database has been started by the server. All I need to know is how to send the data over to the server!

I'm clearly new to javascript and producing this application is part of learning the language along with MongoDB. I've structured this application similarly to an example tutorial book. One difference is that in the tutorial the traffic is two ways between client and server.

Any help is appreciated!

如果将客户端的post的第一个参数从“ npi_checks”更改为“ / checkbox”以匹配第一个参数app.post,则数据将到达服务器并加载到mongoldb中,这是简单的解决方案。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM