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
});
Related
I want to create html content that looks something like this using node.js.
<div class="outputs">
...
</div>
I have the following code:
var mongoose = require("mongoose");
var express = require("express");
var bodyParser = require("body-parser");
var Url = require("./models/Url");
var shortId = require("shortid");
var http = require("http");
var app = express();
var { JSDOM } = jsdom;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.connect(process.env.MLAB_URI);
app.get("/urls", (req, res, next) => {
Url.find({}, function(err, data) {
res.json(data);
console.log(data.length);
});
});
app.get("/deletebase", (req, res, next) => {
Url.deleteMany({}, function(err, data) {
res.json(data);
});
});
app.use(express.static(__dirname + "/"));
app.get("/:shortUrl", function(req, res, next) {
Url.findOne({ shortUrl: req.params.shortUrl }, function(err, findUrl) {
if (err) console.log(err);
if (!findUrl) {
return next({ status: 400, message: "unknown shorturl" });
}
res.redirect(findUrl.longUrl);
});
});
app.post("/", function(req, res) {
var url = new Url(req.body);
var hostname = req.headers.host;
var expression = /[-a-zA-Z0-9#:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()#:%_\+.~#?&//=]*)?/gi;
var regex = expression;
if (regex.test(url) === true) {
url.shortUrl = shortId.generate();
url.fullUrl = "https://" + hostname + "/" + url.shortUrl;
url.save(function(err, savedUrl) {
if (err) console.log(err);
res.redirect("https://" + hostname);
});
} else {
res.redirect("https://" + hostname);
}
});
var options = {
runScripts: "dangerously",
resources: "usable"
};
app.listen(3000, function() {
console.log("RUNNING");
});
I want to get length of the data and create that many div objects with longUrl and shortUrl objects in it. Also when database will be updated new div object should be created, and when I delete database information all the div elements should be deleted too, is this possible to do?
You should be using a templating engine for this the two most popular ones for Node.js are pug(formerly Jade) and hbs(Handlebars.js).
There are a lot of other template engines here you could consider.
I am new to Node JS, so things are not coming easy to me. The scenario is I have input field which will accept multiple files.
<input id="upload-input" type="file" name="uploads[]" multiple="multiple">
in my JS script I grab the the change event of this field, and create a post request to my uploader app which is running in different port using formData and ajax post method
$('#upload-input').on('change', function() {
var files = $(this).get(0).files;
if (files.length > 0) {
var formData = new FormData();
formData.append('directory', "path/to/directory");
for (var i = 0; i < files.length; i++) {
var file = files[i];
formData.append('uploads[]', file, file.name);
}
$.ajax({
url: 'https://myurl.com:3000/upload',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(data) {
console.log(data);
},
});
}
});
Now the file is sending and in my backend I can upload that using formidable, but the problem is I cannot get the directory value, Here is my code
require('dotenv').load();
var express = require('express');
var app = express();
var path = require('path');
var formidable = require('formidable');
var fs = require('fs');
var session = require('express-session');
app.set('views', __dirname + '/public');
app.use('/uploads', express.static(process.env.USER_UPLOADS))
var cors=require('cors');
app.use(cors({origin:true,credentials: true}));
app.post('/upload', function(req, res) {
var user_folder = "path/to/directory/";
var form = new formidable.IncomingForm();
form.multiples = true;
form.uploadDir = path.join(__dirname, process.env.USER_UPLOADS + user_folder);
form.on('file', function(field, file) { fs.rename(file.path, path.join(form.uploadDir, file.name)); });
form.on('error', function(err) { console.log('An error has occured: \n' + err); });
form.on('end', function() { res.end('success'); });
form.parse(req);
});
var server = app.listen(3000, function(){
console.log('Server listening on port 3000');
});
I tried
console.log(req.body)
but it returns undefined, So how can I get the directory value from my backend?
Thanks in advance.
To fix your issue, I made some changes to your main app's server file
i.e. server.js/app.js/index.js anyone that applies to you. See changes below:
require('dotenv').load();
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
var formidable = require('formidable');
var fs = require('fs');
var session = require('express-session');
var cors=require('cors');
app.set('views', __dirname + '/public');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors({ origin:true, credentials: true }));
app.use('/uploads', express.static(process.env.USER_UPLOADS));
app.post('/upload', function(req, res) {
var user_folder = "path/to/directory/";
var form = new formidable.IncomingForm();
form.multiples = true;
form.uploadDir = path.join(__dirname, process.env.USER_UPLOADS + user_folder);
form.on('file', function(field, file) { fs.rename(file.path, path.join(form.uploadDir, file.name)); });
form.on('error', function(err) { console.log('An error has occured: \n' + err); });
form.on('end', function() { res.end('success'); });
// Note the changes here
form.parse(req, (error, fields, files) => {
console.log(JSON.stringify({
fields, // { directory: "path/to/directory" }
files // contains the uploaded files
}), null, 2);
});
});
var server = app.listen(3000, function(){
console.log('Server listening on port 3000');
});
According to the docs at here, form.parse can take an optional callback function.
Parses an incoming node.js request containing form data. If cb is provided, all fields and files are collected and passed to the callback:
form.parse(req, function(err, fields, files) {
// ...
});
I'm trying to re-render my pug template through setInterval().
I'm trying to have a page display live data from a MySQL server. I can get the data to the page but I don't know how to update the data shown without refreshing the entire page.
I've attempted to implement AJAX and also tried to do this via socket.io but failed to send the data to the pug template on both attempts.
Server.js
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var pug = require('pug');
var io = require('socket.io').listen(server);
var clients = [];
var outsideData = require('./public/data.js');
app.set('views', __dirname + '/views');
app.set('view engine', 'pug');
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.render('index.pug', {
data: outsideData.getData()
});
});
io.sockets.on('connect', function() {
clients.push(io.sockets);
console.log("connected");
});
//Recompile Pug Template
function recompile() {
var pug = require('pug');
var template = require('fs').readFileSync('./views/index.pug', 'utf8');
var pugFn = pug.compile(template, {
filename: './views/index.pug',
pretty: true
});
var renderedTemplate = pugFn({
data: outsideData.getData()
});
}
//Send data every second.
setInterval(function() {
for (i = 0; i < clients.length; i++) {
recompile();
clients[i].emit('data', outsideData.getData());
}
}, 30000);
//Handle diconnected clients.
io.sockets.on('disconnect', function() {
var index = clients.indexOf(io.socket);
if (index != -1) {
clients.splice(index, 1);
}
});
server.listen(3001);
index.pug
doctype html
html
head
title Socket Communication
script(src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js')
script(src="/socket.io/socket.io.js")
//script(src="client.js")
var socket = io.connect();
socket.on('data', function(data) {
var myData = $('myData');
console.log(data)
});
body
h1= "Help me..."
p= JSON.stringify(data)
Update:
Here are the changes that works. Thank you mk12ok.
Server.js
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var pug = require('pug');
var io = require('socket.io').listen(server);
var clients = [];
var outsideData = require('./public/data.js');
app.set('views', __dirname + '/views');
app.set('view engine', 'pug');
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.render('index.pug');
});
io.sockets.on('connect', function() {
clients.push(io.sockets);
console.log("connected");
});
//Send data every second.
setInterval(function() {
for (i = 0; i < clients.length; i++) {
clients[i].emit('data', outsideData.getData());
}
}, 1000);
//Handle diconnected clients.
io.sockets.on('disconnect', function() {
var index = clients.indexOf(io.socket);
if (index != -1) {
clients.splice(index, 1);
}
});
server.listen(3001);
index.pug
doctype html
html
head
title Socket Communication
script(src="/socket.io/socket.io.js")
//script(src="client.js")
body
h1= "Help me..."
p(id="data")
script.
var socket = io.connect();
socket.on('data', function(data) {
//Replace JSON.stringify(data) with JSON.stringify(data.tag) to retrieve a specific value stored in your JSON data.
document.getElementById("data").innerHTML = "Received" + JSON.stringify(data);
console.log(data)
});
Instead of re-rendering the pug file you can try this:
your server (very much the same code):
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const pug = require('pug');
app.set('views', __dirname + '/views');
app.set('view engine', 'pug');
app.get('/', function(req, res) {
res.render('index.pug');
});
setInterval(function() {
io.emit('data', 'random number: ' + Math.random().toString());
}, 1000);
io.on('connection', function (socket) {
console.log('client connected');
socket.on('disconnect', function() {
console.log('client disconnected');
});
});
http.listen(3001, function(){
console.log('listening on *:3001');
});
and an example of index.pug:
doctype html
html
head
title Testing socket.io
body
h1 Testing socket.io
br
h3(id="status") not connected
br
p(id="data")
script(src="/socket.io/socket.io.js")
script.
var socket = io();
socket.on('connect', function() {
document.getElementById("status").innerHTML = "connected";
});
socket.on('data', function(data) {
document.getElementById("data").innerHTML = "Received " + data;
});
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();
Hi I am pretty new to NodeJs and I am trying to write my first tests.
I am kind of stuck with the setup, so I was hoping for some help.
I wrote these two functions:
app.js:
var express = require('express')
, cors = require('cors')
, app = express();
app.get('/a_nice_jsonp',cors(corsOptions), function(req, res, next){
var result = parseCookies(req);
res.jsonp(result);
});
app.get('',function(req,res,next){
res.statusCode = 200;
res.end()
});
I do not export it as module as it is my only file.
I assume it's pretty easy to write the tests for that. I started with something like this:
app-test.js:
var expect = require('expect.js');
var express = require('express');
var expressApp = express();
describe('app js test', function() {
describe('GET /', function() {
it('should respond to GET with empty path', function () {
expressApp.get('', function(req, res, body){
expect(res.status).to.equal(200);
});
})
});
});
I suppose it really reads like a simple task, but I seem to fail over the setup of the test and how to do it.
Can anyone help me out here?
EDIT: The above test runs fine. However, I have difficulties to test e.g. .end() as well as the result in the jsonp request. I simple do not know how to do it?!
When you do
expressApp.get('', function(req, res, body){
expect(res.status).to.equal(200);
});
you are just mapping the route.
To test your REST API, you have to use a library like supertest (there is an example of testing using express + mocha in that link)
it works this way
var request = require('supertest');
var express = require('express');
var app = express();
app.get('/a_nice_jsonp',cors(corsOptions), function(req, res, next){
var result = parseCookies(req);
res.jsonp(result);
});
app.get('',function(req,res,next){
res.statusCode = 200;
res.end()
});
describe('app js test', function() {
describe('GET /', function() {
it('should respond to GET with empty path', function (done) {
request(app)
.get('')
.expect(200)
.end(done)
});
});
});
Edited with separated files
app.js
var express = require('express')
, cors = require('cors')
, app = express();
app.get('/a_nice_jsonp',cors(corsOptions), function(req, res, next){
var result = parseCookies(req);
res.jsonp(result);
});
app.get('',function(req,res,next){
res.statusCode = 200;
res.end()
});
module.exports = app;
app-test.js
var request = require('supertest');
var app = require('app.js');
describe('app js test', function() {
describe('GET /', function() {
it('should respond to GET with empty path', function (done) {
request(app)
.get('')
.expect(200)
.end(done)
});
});
});