简体   繁体   English

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

[英]How to send JSON data from client to node.js server.

Here is server.js 这是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. 客户端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);
    });
});

The Chrome console responds immediately with GET http://127.0.0.1:3000/html/checkbox.json 404 (Not Found) Chrome控制台会立即以GET http://127.0.0.1:3000/html/checkbox.json 404响应(未找到)

The page loads and will accept data which the secA.js script formats as JSON. 该页面将加载并接受secA.js脚本格式为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. 我显然不是Java语言的新手,开发此应用程序是与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中,这是简单的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Node.js从客户端向服务器发送json请求 - use Node.js to send a json request from client to the server 如何将数据作为响应从Node.js服务器发送到AJAX客户端? - How do I send data as a response from Node.js server to AJAX client? 如何从Node.js socket.io服务器向浏览器客户端发送二进制数据? - How to send binary data from a Node.js socket.io server to a browser client? 如何使用node.js将表单数据从客户端脚本发送到服务器脚本 - How to send form data from client script to server script using node.js 如何将html数据从html页面发送到node.js服务器 - how to send json data from html page to node.js server 如何使用Node.js从Node.js发送和获取JSON数据到HTML - How to send and get JSON data from Node.js into HTML using Node.js 如何从node.js服务器获取格式化的JSON数据? - how to get formated JSON data from node.js server? 从 node.js 向客户端 js 发送数据的最佳方式 - Best way to send data to client js from node.js 如何将二进制数据从Node.js socket.io(v2.0.x)服务器发送到浏览器客户端? - How to send binary data from a Node.js socket.io (v2.0.x) server to a browser client? 以gzip格式从node.js服务器向客户端发送socket.io响应数据 - Send socket.io response data to client from node.js server in gzip format
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM