I am trying to make a web service that scrapes data from a site but the one I made is not displaying on my browser. I am using Nodejs with Express framework.
My scores.js works, I can get JSON data from it if I run it on the command prompt but when I run it under the Express framework, nothing shows up on my browser.
This is the code I am using for my server.js
var express = require('express');
var scores = require('./scores');
var app = express();
var port = process.env.PORT || 80;
var router = express.Router();
router.use(function(req, res, next) {
console.log('%s %s', req.method, req.path);
next();
});
router.get('/scores', function(req, res, next) {
res.json({result : scores.getAll()});
});
app.use('/api', router);
app.listen(port);
console.log('Server listening on port ' + port);
And this my code for scores.js
var cheerio = require('cheerio');
var requestify = require('requestify');
var rl = require('readline');
var prompts = rl.createInterface(process.stdin, process.stdout);
exports.getAll = function() {
var jsonResponse;
requestify.get('http://example.com').then(function(response) {
var _response = {
'results' : []
};
var title, link, runtime;
response.getBody();
$ = cheerio.load(response.body);
$('.content').each(function() {
$(this).find('a, img, span').each(function(i, elem) {
if ($(this).is('img'))
title = ($(this).attr('alt'));
if ($(this).is('a') && $(this).attr('class') != 'preview')
link = ($(this).attr('href'));
if ($(this).is('span') && $(this).attr('style') == 'float:left;')
runtime = ($(this).text().replace('time:', ''))
});
_response.results.push({"title" : title, "link" : link, "runtime" : runtime});
});
var jsonResponse = JSON.stringify(_response);
});
return jsonResponse;
}
prompts.question("Hit Enter to exit...\n", function() {
process.exit();
});
You have this line:
res.json({result : scores.getAll()});
in your server.js. However, the scores.js does not have the corresponding method getAll().
Related
Was trying to connect to jaeger using HTTP request using nodejs but the spans are not reaching the jaeger endpoint. please help with this code snippet.,
var initTracer = require('jaeger-client').initTracer;
var config = {
'serviceName': 'servicename1',
'reporter': {
'collectorEndpoint': 'http://jaeger-collector:14268/api/traces',
}
};
var options = {
tags: {
'servicename1': '1.0'
}
};
var tracer = initTracer(config, options);
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
app.get('/', (req, res) => {
const span = tracer.startSpan('http_request');
res.send('Hello Jaeger');
span.log({'event': 'request_end'});
span.finish();
});
app.get('/', function(req, res) {
res.send("Hello World!");
});
server.listen(3000);
console.log('Express server started on port %s', server.address().port);
Any help would be much appreciated!
Got it! We need to enable sampling strategy to reach the collector endpoint.
var initTracer = require('jaeger-client').initTracer;
var config = {
'serviceName': 'Jaeger_Service',
'reporter': {
'collectorEndpoint': 'http://jaeger-collector:14268/api/traces',
},
'sampler': {
'type': 'const',
'param' : 0.1
}
};
var options = {
'logger': {
'info': function logInfo(msg) {
console.log('INFO ', msg)
},
'error': function logError(msg) {
console.log('ERROR', msg)
}
}
};
var tracer = initTracer(config, options);
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
app.get('/', (req, res) => {
const span = tracer.startSpan('http_request');
res.send('Hello Jaeger');
span.log({'event': 'request_end'});
span.finish();
});
server.listen(8000);
console.log('Express server started on port %s', server.address().port);
I want to delete Folder/File in client side (Using javascript/Jquery/AngularJS1). I was Searching, finally i got using Node.js it can be done in Sitepoint link. Now iam not getting how to set up Node.js fs(File System) with either of the language.(Prefered language is AngularJS1). Looking for solution.
Thanks in advance.
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.get('*', function (req, res) {
console.log(req.path);
var path = req.path;
if(req.path == '/'){
res.sendFile( __dirname + "/" + "index.html" );
}else
{
res.sendFile( __dirname + req.path);
}
});
app.post('/app',function (req, res) {
console.log(req.body)
var action = req.body.action;
var data = req.body.data;
var fname = req.body.fileName;
switch(action) {
case 'upLoad':
function decodeBase64Image(dataString) {
var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/),
response = {};
if (matches.length !== 3) {
return new Error('Invalid input string');
}
response.type = matches[1];
response.data = new Buffer(matches[2], 'base64');
return response;
};
var imageBuffer = decodeBase64Image(data);
var newPath = __dirname + "/app/images/" + fname;
fs.writeFile(newPath, imageBuffer.data, function(err) {
res.send({confirm : "uploaded" , filename:fname });
});
default:
}
})
var server = app.listen(8080, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
Hi this is Application Folder which i had used.
In this Server.js file where i included node.js modules and load the application.
I'm writing a REST API on using Express.js. The API needs to accept a video file from the client and upload it to cloudinary. When I use the api to return the file back to the client (as a test) everything works perfectly. When I then try to upload the same file to cloudinary I get an error. the error says:
"file.match is not a function"
I'm not sure what file.match even is or why it is giving me a problem. If anyone else has had this issue how did you solve it?
Below is the code that is giving me issues:
app.js
var express = require('express');
var formidable = require('express-formidable');
var app = express();
app.use(formidable());
var routes = require('./routes');
app.use('/routes', routes);
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log('Express server is listening on port ' + port);
});
routes.js
var express = require('express');
var cloudinary = require('../cloudinary.js').cloudinary;
var router = express.Router();
router.post('/upload', function(req, res, next) {
cloudinary.uploader.upload(req.files, function(result) {
console.log(result);
});
});
module.exports = router;
cloudinary.js
var cloudinary = require('cloudinary');
cloudinary.config({
cloud_name: 'name',
api_key: 'key',
api_secret: 'secret'
});
module.exports.cloudinary = cloudinary;
I was able to solve the issue. It was not a problem on Cloudinary's end. The key was to only send the location of the file.
WORKING routes.js
var express = require('express');
var cloudinary = require('../cloudinary.js').cloudinary;
var router = express.Router();
router.post('/upload', function(req, res, next) {
var fileGettingUploaded = req.files.fileToUpload.path;
cloudinary.uploader.upload(fileGettingUploaded, function(result) {
console.log(result);
});
});
module.exports = router;
Did you try to specify the resource_type as video -
cloudinary.uploader.upload(req.files,
function(result) {console.log(result); },
{ resource_type: "video" });
If you're uploading images and videos you can use the auto as resource_type.
I have a problem with my nodejs server. Here is my code
server.js
global.jQuery = global.$ = require('jquery');
var express = require('express'),
path = require('path'),
menu = require("./routes/menu");
var sql = require("mssql");
var http = require("http");
var io2 = require("io");
var app = express();
var serve = http.createServer(app);
var io = require('socket.io')(serve);
var recordset2;
var port = 8080;
app.configure(function () {
app.set('views', __dirname + '/views');
app.set('view engine','jade');
/* app.use(express.favicon());*/
app.use(app.router);
app.use(express.static(path.join(__dirname+'public')));
});
app.get('/:viewname', menu.viewname);
io.on('connection', function (socket) {
socket.on('disconnect', function () {
console.log('user disconnected');
});
socket.on('chat', function (msg) {
socket.broadcast.emit('chat', msg);
});
});
var dbConfig = {
server: "localhost",
database: "MyDatabase",
user: "sa",
password: "sa",
port: 1433
};
function getConnected() {
var conn = new sql.Connection(dbConfig);
conn.connect().then(function () {
var req = new sql.Request(conn);
req.query("SELECT * FROM Countries").then(function (recordset) {
console.log("Recordset:", recordset);
conn.close();
}).catch(function (err) {
console.log("Error!!!!");
console.log(err);
conn.close();
});
}).catch(function (err) {
console.log("Error!!!! ----");
console.log(err);
});
}
getConnected();
app.listen(port);
client's code
var socket = io();
$(function () {
$('#get-button').on('click', function () {
console.log("CLICK");
var msg = "HIIII";
socket.emit('chat', msg);
});
});
I'm trying to make a connection between server and client by socket, but it returns me the following error:
Error: Failed to lookup view 'socket.io' in views directory C:\Radio/views;
at Function.app.render (C:\Radio\node_modules\express\lib\application.js:493:17)
at ServerResponse.res.render (C:\Radio\node_modules\express\lib\response.js:798:7)
at exports.viewname (C:\Radio\routes\menu.js:2:9)
at callbacks (C:\Radio\node_modules\express\lib\router\index.js:164:37)
at param (C:\Radio\node_modules\express\lib\router\index.js:138:11)
at param (C:\Radio\node_modules\express\lib\router\index.js:135:11)
at pass (C:\Radio\node_modules\express\lib\router\index.js:145:5)
at Router._dispatch (C:\Radio\node_modules\express\lib\router\index.js:173:5)
at Object.router (C:\Radio\node_modules\express\lib\router\index.js:33:10)
at next (C:\Radio\node_modules\express\node_modules\connect\lib\proto.js:193:15
Could you help me understand why? I saw there is another similar topics but none of the solutions there helped.
I found a solution two minutes after posting this topic.
global.jQuery = global.$ = require('jquery');
var express = require('express'),
path = require('path'),
menu = require("./routes/menu");
var sql = require("mssql");
var http = require("http");
var io2 = require("io");
var app = express();
var port = 8080;
var ser = app.listen(port); //<-----------This solved my problem.
I am trying to build a small app in nodejs to publish and subscribe. I am stucked in how I can publish from client side. Here is the code I have.
Here is my server code (server.js)
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app);
app.use(express.bodyParser());
app.get('/', function(req, res) {
res.sendfile(__dirname + '/public/index.html');
});
app.post('/publish/:channel/:event/', function(req, res) {
console.log("**************************************");
var params = req.params;
console.log(req.params);
console.log(req.body);
var data = req.body;
console.log("**************************************");
var result = io.sockets.emit(params.channel,{event:params.event,data:data});
//console.log(result);
console.log("**************************************");
res.sendfile(__dirname + '/public/index.html');
});
//include static files
app.use(express.static(__dirname + '/public'));
server = server.listen(3000);
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (s) {
socket = s
socket.emit('c1', { hello: 'world' });
socket.on('test', function (data) {
socket.emit('c1', { hello: 'world' });
console.log('test');console.log(data);
});
});
And here is client code
var narad = {};
narad.url = 'http://192.168.0.46:3000';
narad.lisentingChannels = {}
var socket = io.connect(narad.url);
function Channel(channelName) {
this.channelName = channelName; //serviceObject is the object of
this.events = {};
};
Channel.prototype.bind = function (event, callback) {
this.events[event] = callback;
};
narad.subscribe = function (channelName) {
var channel = new Channel(channelName)
this.lisentingChannels[channelName] = channel;
socket.on(channelName, this.callbackBuilder(channel))
return this.lisentingChannels[channelName];
}
narad.callbackBuilder = function (channel) {
return function (data) {
var callback = channel.events[data["event"]];
callback(data.data);
}
}
You can use the emit method on both the client and the server websocket connections, taken from Socket.io:
var socket = io.connect(narad.url);
socket.emit('publish', 'message');
Then on your server you listen for the message:
socket.on('publish', function (data) {
// Emit the published message to the subscribers
socket.emit('subscribers', data);
console.log(data);
});
This way you are using the bi-directional communication of websockets without having to use some POST api.