Created
May 3, 2013 17:08
-
-
Save hugozap/5511423 to your computer and use it in GitHub Desktop.
Enviar POST desde JSON y recibirlo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/****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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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