I want to display all the output from pokecli.py on a web page that can be accessed from http://192.168.32.100:8081. Currently I am getting a "connection refused" from Chrome, but no errors when running node myscript.js.
I am new to Node and I am not exactly sure if this is right. I want to display the output in real time. I know this is possible even without NGINX since I can get output from the following example code by opening http://192.168.32.100:8080:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(8080, '192.168.0.251');
console.log('Server running at http://192.168.0.251:8080/');
Here is my code:
var http = require('http');
var PythonShell = require('python-shell');
var express = require('express');
var app = express();
// Options to be used by request
var options = {
host: '127.0.0.1',
port: '8081'
};
// Callback function is used to deal with response
var callback = function(response){
// Continuously update stream with data
var body = '';
response.on('data', function(data) {
body += data;
PythonShell.run('pokecli.py', function (err) {
if (err) throw err;
console.log('finished');
});
});
response.on('end', function() {
// Data received completely.
console.log(body);
});
}
// Make a request to the server
var req = http.request(options, callback);
app.get('/', function (req, res) {
res.send('Hello World!'); // This will serve your request to '/'.
});
app.listen(8081, function () {
console.log('Example app listening on port 8081!');
});
req.end();
Related
I am learning node.js and I am trying to figure out how I can get my program to listen at a specific port, but I just keep getting error messages. Is there any easier way I could be doing this, or what do I need to change in my code to allow this to work?
const http = require('http');
const port = 3000
const requestHandler = (request, response) => {
console.log(request.url)
response.end('server is listening!')
}
const server = http.creatServer(requestHandler)
server.listen(port, (err) => ) {
console.log('server is listening on ${port}')
}
I think you should try something like the following to get started.
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello World!');
res.end();
}).listen(8080);
Or in your case, I think that the following changes will work:
const http = require('http');
const port = 3000
const requestHandler = (request, response) => {
console.log(request.url)
response.end('server is listening!')
}
const server = http.createServer(requestHandler)
server.listen(port, (err) => {
console.log('server is listening on ${port}')
})
It seems you had a syntax error as well as a typo in your code.
im writing a webserver in nodeJs as seen in the following code. I got the server working but sadly i cant acces the website outside my network (localhost). How can i do this?
var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(80, function(){
console.log('Server running on 80...');
});
I also used this method to check if the other method was the problem.
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res){
fs.readFile('Index.html', function (err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
})
}).listen(80);
Have you tried binding the port externally ?
connect().use(serveStatic(__dirname)).listen({
host: '0.0.0.0',
port: 80
}, function(){
console.log('Server running on 80...');
});
I am a real noob in JS and Node and am trying to render a JADE view from JSON received from a REST API. When i run the http.request as a standalone it works just fine, but when i start adding modules and the render stamens, I cannot get the http request function to execute.
When i run it in debug it just skips to the end statement. i cannot figure out why.
any help would be really appreciated TIA.
var http = require('http');
module.exports = function() {
var options = {
host: '41.193.214.130',
port: 2510,
path: '/eiftidemo/clt_list',
method: 'GET'
};
var clientsDatag;
http.request(options, function(res) {
var body = '';
//none of these statemnst excecute
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
var clientsData = JSON.parse(body);
var clientsDatag = clientsData;
// this stament doesn't execute either
debugger;
});
}).end();
debugger;
res.render('listlxr', {
details: clientsDatag
});
};
here is the calling script:
var express = require('express');
var bodyParser = require('body-parser');
var tweetList = require('./tweet-list');
var clientList = require('./lxr-clients')
var app = express();
app.set('view engine', 'jade');
app.use(bodyParser.urlencoded({
extended: false
}))
app.get('/', function(req, res) {
res.render('index');
});
app.post('/get_tweets', function(req, res) {
var screen_name = req.body.handle;
var tweets = tweetList(res, screen_name);
});
app.get('/get_clients', function(req, res) {
var clientd = clientList(res, req);
});
var server = app.listen(3000, function() {
console.log('Our App is running at http://localhost:3000');
});
many thanks to anyone who can help
app.get('/get_clients', function(req, res) {
var options = {
host: '41.193.214.130',
port: 2510,
path: '/eiftidemo/clt_list',
method: 'GET'
};
http.request(options, function(details) {
res.render('listlxr', {
details: details
});
});
});
Try adding an error-handler and see if you get anything there:
var request= http.request(options, function(res) {...});
request.on('error', function(err){
// Handle error
});
I have a very simple server like this:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
fs.readFile('index.html', 'utf-8', function (err, content) {
if (err) {
res.end('something went wrong.');
return;
}
res.end(content);
});
}).listen(8080);
console.log("Server running on port 8080.")
This takes care of rendering my html, but now I want to send an object. Something like this:
var arr = [1,2,3];
I want to be able to manipulate this object on the client side using js. So in addition to knowing how to send it from server to client, I would like to know how to receive it in the client, if that makes sense.
I am trying to learn how things happen behind the scene so I do not want to use express.
The only thing you can exchange via HTTP protocol in general is data. Not objects, not html files, just data.
The process of converting objects to data and back is called serialization.
For your specific case of simple objects, you can use JSON built-in object to serialize your objects.
At server:
var data = JSON.stringify(arr);
res.end(data);
At client:
var arr = JSON.parse(data);
As to how to ask and receive data on client, try googling XmlHTTPRequest.
On request, adding fully functional server-side code:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': '*' });
var data = JSON.stringify([1, 2, 3]);
res.end(data);
}).listen(8080);
console.log("Server running on port 8080.")
the Access-Control-Allow-Origin header was only necessary to be able to run your code in console (it is called 'CORS' and means this endpoint can be requested from pages hosted on other domains)
Simply change the response type and stringify the JSON:
http.createServer(function (req, res) {
var arr = [1,2,3];
res.writeHead(200, { 'Content-Type': 'application/json'});
res.end(JSON.stringify(content), 'utf-8');
}).listen(8080);
Ok so seems like I was doing a few things wrong. It mainly had to do with the routing on the server. This is what I had tried to do:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
var arr = [1, 2, 3];
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(arr), 'utf-8');
}).listen(8080);
console.log("Server running on port 8080.")
And on client side I had something like this:
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://localhost:8080/", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
console.log(JSON.parse(xmlhttp.responseText));
}
}
xmlhttp.send();
For some reason, the console.log would never happen and I would just get the array printed on the page. But by adding some routes to my server like this, it worked:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
if (req.method === 'GET' && req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html' });
fs.readFile('index.html', 'utf-8', function (err, content) {
if (err) {
res.end('something went wrong.');
return;
}
res.end(content);
});
}
if (req.method === 'GET' && req.url === '/data') {
var arr = [1, 2, 3];
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(arr), 'utf-8');
}
}).listen(8080);
console.log("Server running on port 8080.")
I have a movie-finding app that makes API calls in the backend. During initialization I need to load some JSON files: one (lang.json) contains a list of languages for searching purposes, the other (stored in the config variable) is used to get a link to the movie poster.
How would I ensure the loading of these files is completed before an HTTP request is made? One solution I can think of involves putting the calls to app.get() and app.listen() inside fs.readfile()'s callback. But is there a better way? Web development is totally new to me.
var express = require('express');
var app = express();
var fs = require('fs');
var request = require('request');
var merge = require('merge');
require('dotenv').config();
var apiKey = process.env.API_KEY;
var config = {};
app.use(express.static('view'));
// TODO load config and lang before below code
app.get('/lang', function(req, res) {
fs.readFile('lang.json', function(err, data) {
if (err) throw err;
res.json(JSON.parse(data));
});
});
app.get('/genres', function(req, res) {
request.get({
url: 'http://api.themoviedb.org/3/genre/movie/list',
qs: {api_key: apiKey}
}, function(error, response, body) {
res.json(JSON.parse(body).genres);
});
});
app.get('/randomMovie', function(req, res) {
request.get({
url: 'https://api.themoviedb.org/3/discover/movie',
qs: merge(req.query, {api_key: apiKey})
}, function(error, response, body) {
body = JSON.parse(body).results;
var len = body.length;
var i = Math.floor(Math.random() * len);
var movie = body[i];
// movie.poster_path = movie.images.base_url + movie.images.poster_sizes[6] + movie.poster_path;
res.json(movie);
});
});
app.listen(3000, function() {
console.log('server started on port 3000');
});
The easiest way is to just use fs.readFileSync() before your call to app.listen(). For example:
var lang = fs.readFileSync('lang.json');
app.get('/lang', function(req, res) {
res.setHeader('Content-Type', 'application/json');
res.send(lang);
});
// ...
Just be aware that the contents of lang will not automatically update if the contents of lang.json change on disk during the lifetime of your node process.