2015-01-30 3 views
1

Вот server.jsКак отправить данные JSON с клиента на сервер node.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 мгновенно реагирует с ГЭТ http://127.0.0.1:3000/html/checkbox.json 404 (Не найдено)

загрузки страницы и будет принимать данные, которые форматы secA.js сценария как JSON. База данных была запущена сервером. Все, что мне нужно знать, это как отправить данные на сервер!

Я, очевидно, новичок в javascript, и создание этого приложения является частью изучения языка вместе с MongoDB. Я структурировал это приложение аналогично примеру учебника. Одно из отличий заключается в том, что в учебнике трафик является двумя способами между клиентом и сервером.

Любая помощь приветствуется!

+1

попробуйте URL-адрес http: //127.0.0.1: 3000/checkbox.json' – fmodos

+0

Это готово: GET http://127.0.0.1:3000/checkbox.json net :: ERR_EMPTY_RESPONSE Кроме того, «npi_checks» является исторической реликвией, была изменена на «checkbox» – user2970900

+0

Трюк, похоже, заключается в определении первого аргумента для .getJSON() и .post() – user2970900

ответ

0

Если первый аргумент пост, на стороне клиента, изменяется с «» npi_checks»до„/ флажок“в соответствии с первым аргументом app.post данные попадают на сервер и загружается в mongoldb. Это простое решение.

Смежные вопросы