Skip to content

Instantly share code, notes, and snippets.

@hugozap
Created May 3, 2013 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hugozap/5511423 to your computer and use it in GitHub Desktop.
Save hugozap/5511423 to your computer and use it in GitHub Desktop.
Enviar POST desde JSON y recibirlo
/****Cargar archivo JSON de clientes****/
var http = require('http');
var fs = require('fs');
var querystring = require('querystring');
fs.readFile('Clientes.json', 'utf8', function (err, data) {
if (err) {
throw err;
}
var objData = JSON.parse(data);
hacerPost(objData);
});
function hacerPost(data){
var collectionName = "personas";
var post_options = {
host: 'localhost',
port: 3000,
path: '/crearRegistros',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset = utf8'
}
}
var post_data = querystring.stringify({
"collection" : collectionName,
'data' : data
});
post_options.headers['Content-Length'] = post_data.length;
// Set up the request
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
});
});
post_req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
post_req.write(post_data, 'utf8');
post_req.end();
}
var express = require('express');
var http = require('http');
var path = require('path');
var mongo = require('mongoskin');
var mongouri = 'localhost:4000/mydb';
var app = express();
app.use(express.bodyParser());
app.post("/crearRegistros", function(req, res){
console.log("body: " , req.body);
var doc = req.body;
console.log('La colección es:',doc.collection);
res.send("OK");
});
/*** config app.get***/
app.get('/people.json', function(request, response) {
response.contentType('application/json');
var db = mongo.db(mongouri,{safe:true});
db.collection('personas').findOne({id:190}, function(error,result){
if(error) throw error;
response.send(result); //retorna registro encontrado
console.log(result);
});
});
app.listen(3000);
console.log('listening to http://localhost:3000');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment