How can I fetch req.param and get body in Node.js? - node.js

I found this example to get body, but how can I retrive the req.param variable? I do not have req in this case?!
app.post('/:tableName', function(res){
var data = '';
res.on('data', function (chunk){
data += chunk;
});
res.on('end',function(){
var obj = JSON.parse(data);
var schema = require('./schema/' + req.param('tableName'));
var record = new schema(obj);
record.save(function(err) {
if (err) {
console.log(err);
res.status(500).json({status: 'failure'});
} else {
res.json({status: 'success'});
}
});
})
});
UPDATE
I modified the method signature like this, but then first res.on will not get called.
app.post('/:tableName', function(req, res) {

Your callback should take in req and res, but is currently only taking in req as res.
app.post('/:tableName', function(req, res){ should give the function what it expects.

Related

Retrieving key/value from form-data post from client

I write API in order to client upload file. API has content-type multiple/form-data. But I don't know get values from client send to my
router.post('/upload/file', async (req, res) => {
var body = "";
try {
req.on('data', function (chunk) {
body += chunk;
});
req.on('end', function () {
console.log('body: ' + body);
var formData = new FormData(body);
console.log("=====================", formData.entries);
// var {accessTok, type, file} = req.params;
//
// if (!accessTok || !type || !file) {
res.json({
code: -1000,
message: 'Missing parameter(s). Please provide accessToken, type upload, file upload.'
});
res.end();
return null;
})
// }
}catch(err){
res.json({err: err.message});
res.end();
return;
}
I tried use FormData but not done. I get error is not function, formData.getKey('') is them same.

NodeJs Decode to readable text

PROBLEM
I want to receive data from a device using IP Address via NodeJs. But I received the following data:
What I've Tried
This is the code that I've been able to get, which still produces the problem I described above.
var app = require('http').createServer(handler);
var url = require('url') ;
var statusCode = 200;
app.listen(6565);
function handler (req, res) {
var data = '';
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
console.log(data.toString());
fs = require('fs');
fs.appendFile('helloworld.txt', data.toString(), function (err) {
if (err) return console.log(err);
});
});
res.writeHead(statusCode, {'Content-Type': 'text/plain'});
res.end();
}
And below is the result I received for console.log(req.headers)
So my question is, how do I decode the data? and anyone know what type of data are they?
Use Buffers to handle octet streams.
function handler (req, res) {
let body=[];
req.on('data', function(chunk) {
body.push(chunk);
});
req.on('end', function() {
body = Buffer.concat(body).toString('utf8');
...

Node.js http.get returning "undefined" in function

var exports = module.exports = {};
var http = require('http');
exports.get = function(key, app, vari) {
http.get('<url here>/?key='+key+'&app='+app+'&var='+vari+'&req=0', function (response) {
response.setEncoding('utf8');
response.on('data', function(body) {
console.log(body);
return body;
});
});
};
My code (seen above) will output the response to the console just fine, but when trying to use the function in an export, it returns 'undefined' no matter what. The responses it receives are one line and are in the content type of "application/json". What's up with it? (And no, it's not the "url here", I just removed the URL for privacy reasons. If it helps, I can provide it.)
exports.get = function(key, app, vari) {
return
http.get('<url here>/?key='+key+'&app='+app+'&var='+vari+'&req=0', function (response) {
response.setEncoding('utf8');
response.on('data', function(body) {
console.log(body);
return body;
});
});
};
reference,and you need to listen end event and return a promise instead, just like:
var exports = module.exports = {};
var http = require('http');
exports.get = function(key, app, vari) {
return new Promise(function(resolve) {
http.get('<url here>/? key='+key+'&app='+app+'&var='+vari+'&req=0', function (response) {
response.setEncoding('utf8');
var data = '';
response.on('data', function(chunk) {
console.log(chunk);
data += chunk;
});
response.on('end', function() {
resolve(JSON.parse(data));
});
});
})
}
I figured it out, I just needed to have a call for an answer.
var exports = module.exports = {};
var http = require('http');
exports.get = function(key, app, vari, answ) {
http.get('http://<url here>/?key='+key+'&app='+app+'&var='+vari+'&req=0', function (response) {
response.setEncoding('utf8');
response.on('data', function(body) {
answ(body);
});
});
};

Return object from REST call

I'm pretty new at node, so I may be going about this all wrong (if I am, don't be afraid to say) - I'd like to be able to create an object made of data from several different rest servers and return the final object to my calling function. For each rest api I have a function that looks a bit like this:
jobs.js
exports.get_users_jobs = function(options, onResult) {
var user = options.params.user;
console.log("Get jobs for user: " + user);
var optionsget = {
host: config.jobs_rest_host,
port: config.jobs_rest_port,
path: "/jobs3/user/" + user,
method: "GET",
headers: {
'Content-Type': 'application/json'
}
};
var reqGet = http.request(optionsget, function(res) {
var output = '';
res.setEncoding('utf-8');
res.on('data', function(chunk) {
output += chunk;
});
res.on('end', function() {
var obj = JSON.parse(output);
onResult.send(res.statusCode, obj);
});
});
reqGet.end();
reqGet.on('error', function(e) {
console.error('error: ' + e.message);
});
};
That works fine when I'm calling it directly from the browser, but now I'd like to call get_users_jobs from another function, take the data and plonk that into my uber object. So I've created something a bit like this (I've only put jobs in there for now, but soon there will be other variables)
users.js
var jobs = require('./jobs.js');
function User (jobs) {
this.jobs = jobs;
}
User.prototype.jobs = null;
/* lots of stuff that I don't think matters */
jobs_data = jobs.get_cb_users_jobs(req, res);
var u = User(jobs_data);
/* do lots of stuff with u like prepare reports etc */
But all that happens here is my jobs data is output in the browser (which makes sense since I have onResult.send(blah) - how can I construct my get_users_jobs function to just return the data from the rest call?
Thanks in advance to anyone that can help!
Instead of passing a response to your get_users_jobs, pass it a callback as a second parameter, something like this:
exports.get_users_jobs = function(options, cb) {
//...
//no changes
//...
var reqGet = http.request(optionsget, function(res) {
var output = '';
res.setEncoding('utf-8');
res.on('data', function(chunk) {
output += chunk;
});
res.on('end', function() {
var obj = JSON.parse(output);
cb(null, {
status: res.statusCode,
data: output
});
});
});
reqGet.end();
reqGet.on('error', function(e) {
cb(err);
});
};
and then in users.js:
jobs.get_cb_users_jobs(req, function(err, result) {
if (err) {
//handle the error
} else {
//do whatever you want with the result
}
});
Notice the call to callback inside res.on('data', ...) and res.on('error', ...) - this is a typical node.js callback pattern. You did the same thing, but passed the control to response instead of your own function.
If you still need to pass the result directly to response, add a wrapper function that passes
function(err, response) {
if (err) {
console.error('error: ' + e.message);
} else {
onResult.send(res.statusCode, obj);
}
}
as callback parameter to get_users_jobs

I am trying to read image from different server and write on response

function media(req,res){
console.log(req.query.image);
var collectionName = 'imageTable';
var selector = MongoHelper.idSelector(req.query.image);
MongoHelper.findOne(selector, collectionName, function(err, image) {
console.log(image.picture);
var url_parts = url.parse(image.picture);
var options = {host: url_parts.hostname, path: url_parts.pathname};
http.get(options).on('response', function (response) {
var body = '';
var i = 0;
response.on('data', function (chunk) {
i++;
body += chunk;
console.log('BODY Part: ' + i);
});
response.on('end', function () {
console.log('Finished');
res.writeHead(200,{'Content-Type':'image/JPEG'});
res.write(body);
res.end();
});
});
});
}
I am fetching image from different server. I have url of that image. And I am writing the response. But here response image is get corrupted. Any idea about how to write jpeg image in response?
function media(req,res){
console.log(req.query.image);
var collectionName = 'facebook';
var selector = MongoHelper.idSelector(req.query.image);
MongoHelper.findOne(selector, collectionName, function(err, image) {
var url_parts = url.parse(image.picture);
var options = {host: url_parts.hostname, path: url_parts.pathname};
http.get(options).on('response', function (response) {
res.writeHead(200,{'Content-Type':'image/JPEG'});
response.on('data', function (chunk) {
res.write(chunk);
});
response.on('end', function () {
res.end();
});
});
});
}
Here I got the solution. Instead of writing whole data at the end. Write it each time you get and end the response when you reach to the end of file. But still if anyone have better idea can write here.

Resources