I want to do a very simple task, yet I am stuck!
The scenario is like this:
After a get request to my api, I want to http.get from some external site, and then send back the response from this external site to the original api request.
Obviously, the calls are asychronous so the string loremParagraph, doesn't load correctly before sending it back to the api.
Also I get the error: Error: Can't set headers after they are sent.
Here is my code:
module.exports = function(app, express) {
var myLoremRouter = express.Router();
var loremParagraph = '';
//HTTP GET accessed at localhost:8081/mylorem
myLoremRouter.get('/', function(req, res) {
// Fetch one paragpraphlorem ipsum text from http://www.faux-texte.com/text-random-1.htm
http.get("http://www.faux-texte.com/text-random-1.html", function(resp) {
resp.on('data', function(chunk) {
// console.log('BODY: ' + chunk);
var $ = cheerio.load(chunk);
loremParagraph = $('div.Texte').text();
console.log(loremParagraph);
// console.log(resp.status);
});
})
// If any error has occured, log error to console
.on('error', function(e) {
console.log("Got error: " + e.message);
});
//Finally send the result back to the api call
res.json({ message: loremParagraph });
});
return myLoremRouter;
};
Try this. Here chunks are added till we are ready to use the complete data.
https://stackoverflow.com/a/21953201/6219247
myLoremRouter.get('/', function(req, res) {
var body = '';
http.get({
host: 'www.faux-texte.com',
port: 80,
path: '/text-random-1.html'
}, function(resp) {
resp.on('data', function(chunk) {
body += chunk;
});
resp.on('end', function(chunk) {
var $ = cheerio.load(body);
loremParagraph = $('div.Texte').text();
res.json({ message: loremParagraph });
});
})
.on('error', function(e) {
// handle/send error
res.send(/*...*/);
});
});
Related
Im following a article about http requests to nasa's pic of the day. I'm trying to display the JSON object in browser from my server. But all Node.js' examples outputs the api results to a server's console. is it possible to have my server save/forward the response to the browser? I'd like to understand the native http module before relying on any dependencies. Also I'm not sure if it makes a difference but I'm using express to create my server. anything will help even a high level explanation because I'm so confused.
const https = require('https');
app.get('/', (req, res) => {
var url = 'https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY';
var nasa_obj
var request = https.get(url, function (resp) {
var body = '';
resp.on('data', function (chunk) {
body += chunk;
});
resp.on('end', function () {
nasa_obj = JSON.parse(body);
console.log("Got a response: ", nasa_obj);
res.send(nasa_obj)
});
}).on('error', function (e) {
console.log("Got an error: ", e);
});
request.end()
})
UPDATED: CODE IS CORRECT
You only want to send the response once it has been returned to you:
const https = require('https');
app.get('/', (req, res, next) => {
var url = 'https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY';
var nasa_obj
var request = https.get(url, function (response) {
var body = '';
response.on('data', function (chunk) {
body += chunk;
});
response.on('end', function () {
console.log("Got a response: ", body);
res.send(body);
});
}).on('error', function (e) {
console.log("Got an error: ", e);
next(e); // Pass error to error handling middleware
});
request.end()
})
Also make sure you are properly handling errors. Either send back a response to the browser to, as the code above is doing, pass it on to error handling middleware.
I am using node's https module to fetch my public profile from facebook. But i am getting 302 status code in response. Following is the code i am using:
var https = require('https');
var options = {
hostname: 'www.facebook.com',
path: '/suri.nik',
method: 'GET'
};
var results = '';
var req = https.request(options, function (res) {
console.log('STATUS CODE : ' + res.statusCode);
res.on('data', function (chunk) {
results = results + chunk;
});
res.on('end', function () {
console.log(results);
});
res.on('error', function () {
console.log('error here');
});
});
req.on('error', function (e) {
console.log('error in ur request: ' + e);
});
req.end();
I am getting STATUS CODE : 302, i should be getting status code : 200 with valid html in response of my profile. I am able to fetch the public profile from my browser or postman using the same link(www.facebook.com/suri.nik) Where lies the issue? is it the way i am making my request?
I have a simple http.get request to external api.
How can I access id and name variables from another function? Thanks!
app.use(function *(next){
var name = '';
var id = '';
var options = {
host: 'www.website.com',
path: '/json/somedata',
metohd: 'GET'
};
http.get(options, function(res) {
var body = '';
res.on('data', function(chunk) {
body+=chunk;
console.log(body);
})
res.on('end', function() {
var parsed = JSON.parse(body);
id = parsed.id;
name = parsed.name;
})
})
});
I guess you are using the npm module express, with the syntax you have there.
Your answer depends on where you are looking to use id and name. If you are trying to use it in a route or middleware after this one a common way to solve that problem is to attach the properties (in this case name and id) to the request. Remember to call next after you are finished otherwise express will not know you have finished all your processing
I've given a quick example below:
app.use(function (req, res, next){
var options = {
host: 'www.website.com',
path: '/json/somedata',
method: 'GET'
};
http.get(options, function(getResponse) {
var body = '';
getResponse.on('data', function(chunk) {
body+=chunk;
console.log(body);
})
getResponse.on('end', function() {
var parsed = JSON.parse(body);
req.id = parsed.id;
req.name = parsed.name;
next();
})
})
});
I'm currently designing a UI for an Automated Parking System. I currently need to test if my page sends out data from a form by sending it to a listener. I currently have this code but I'm not sure why it isn't working. Any help would be greatly appreciated.
This is my code that sends the data to a local listener.
<script>
var INPARK = {cardID: $("#ticket_num").val(), lift: 1, floor: 1};
$.ajax({
type:"POST",
url: '192.168.150.148:5007',
contentType:"application/json",
data: JSON.stringify(INPARK)
});
</script>
This is the listener code.
var HOST = '192.168.150.148'; // This should be your IP of 192.168.150.XXX
var PORT = 5007;
var http = require('http');
http.createServer(function (req, res) {
// Only listen for POST requests
if (req.method === 'POST') {
var buffer = '';
req.on('data', function (chunk) {
buffer += chunk;
});
req.on('end', function () {
var path = req.url.substring(0, req.url.indexOf('/', 1)).toUpperCase();
var json;
try {
json = JSON.parse(buffer);
} catch (err) {
//
}
if (path === '/INPARK') {
// Handle INPARK request
console.log(json);
res.write('inpark results');
} else if (path === '/OUTPARK') {
// Handle OUTPARK request
console.log(json);
res.write('outpark results');
} else {
// Do nothing - Bad request
res.write('BAD REQUEST');
}
// Close the connection
res.end();
});
}
}).listen(PORT, HOST, function () {
console.log('Listening at %s:%s', HOST, PORT);
});
Your ajax request is most likely going from port 80 or 443 to 5007, which is a cross domain request, hence it will fail,
If you want to resolve this issue, read up on CORS:
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing,
and JSONP:
https://en.wikipedia.org/wiki/JSONP
I have a node.js Server:-
// *********** Server that receives orders ************ //
// to use features of the http protocol. //
var http = require('http');
// initialize to empty string. //
var req = "";
// create the server that will receive an order Request. //
var server = http.createServer(function(req,res) {
res.writeHead(200, {'content-type': 'text/plain'});
// when data is successfully received, a success message is displayed. //
res.on('data', function(data){
req += data; // received data is appended. //
console.log("We have received your request successfully.");
});
});
// An error message is displayed - error event. //
server.on('error', function(e){
console.log("There is a problem with the request:\n" + e.message);
});
// server listens at the following port and localhost (IP). //
server.listen(8000, '127.0.0.1');
and then I have a node.js Client:-
var http = require("http");
var querystring = require("querystring");
var postOrder = querystring.stringify({
'msg': 'Hello World!'
});
var options = {
hostname: '127.0.0.1',
port: 8000,
path:'/order',
method:'POST',
headers:{
'Content-Type' :'application/x-www-form-urlencoded',
'Content-Length' : postOrder.length
}
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write(postOrder);
req.end();
I am trying to figure out how I can make the client post its order to the server and get a response back from the server...either a success message or an error message...using command line.
currently I run the server on cmd line $ node server.js
and then a run the client $ node client.js
but i get no responses.
I think that have problems from the server:
The Server must be:
http.createServer(function(req, res) {
if (req.method == 'GET') {
} else if (req.method == 'POST') {
var body = '';
req.on('data', function(data) {
body += data;
});
req.on('end', function() {
console.log("We have received your request successfully.");
});
}
res.end("ok");
})