Hello I am new in node js and i am Facing the error.
fb-downloader package is working fine with console.log()
But i want to display results on webpage. But the Express displays only {}
Please Help me.
const getFBInfo = require("fb-downloader");
const express = require("express");
const app = express();
const port = 3016;
app.get("/",function(req, res){
data = getFBInfo("https://www.facebook.com/watch?v=272591278381388");
res.json(data);
});
app.listen(port, function() {
console.log(`Server is listening on port http://localhost:${port}!`)
});
Sorry for Bad English
getFBInfo is an asynchronous operation, therefore use async and await:
app.get("/",async function(req, res){
var data = await getFBInfo("https://www.facebook.com/watch?v=272591278381388");
res.json(data);
});
Related
I am trying to build a REST API for my frontend app using nodejs + express + nats.
I have a nats-server running in my terminal.
This is my test code:
var express = require("express");
var app = express();
const NATS = require('nats');
const nc = NATS.connect();
nc.on('connect', () => {
console.log('connected');
})
nc.publish('foo', 'Hello World!');
app.get('/', (req,res) => {
nc.subscribe('foo', function (msg) {
res.send(msg)
});
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
After running test code, localhost:3000 cannot be reached.
I found a similar project on github: https://github.com/georgehaidar/poc-express-nats/blob/master/api.js.
I cant seem to find my error.
Can anyone plz help me figure out what im doin wrong?
Thank you in advance.
It looks like you've not provided the nats.connect() method with a hostname like the original author does:
const nats = require('nats').connect({'servers': ['nats://nats:4222']})
Nats Connection documentation:
https://docs.nats.io/developing-with-nats/connecting/specific_server
I am writing a server that is meant to serve and receive files. It is written in node.js, using express.js. I also have a client, also written in node, which is meant to send a request to the server and receive the files on the server.
Server-side
const express = require("express");
const app = express();
const file = "./samplefiles/Helloworld.txt";
app.get("/", (res)=>{
res.download(file);
});
module.exports = app; //this exports to server.js
const http = require("http");
const app = require("./app.js);
const port = 8080;
const server = http.createServer(app);
server.listen(port, () => {
console.clear();
console.log("server running");
})
Client-side
const request = require("request");
request.get("http://localhost:8080/", (req, body) => {
console.log(body);
console.log(res);
});
If I try to access it by my browser I am asked what I want to do with the file, it works. However, Is I run my client-side code it prints the body and the res(being null). I expected the file name and it's content to be in the body but only the content of the file was in the body.
I want to receive the whole file, is possible, or at least get the name of it so that I can "make" a copy of it on the client-side.
Change code your server side to:
const port = 8080;
const express = require("express");
const app = express();
const path = require('path');
app.get("/", function(req, res){
res.sendFile(path.join(__dirname, 'app.js'));
});
app.listen(port, () => {
console.clear();
console.log("server running");
});
Change code your client-side to:
var request = require('request');
request('http://localhost:8080/', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print data of your file
});
You need to install request npm i request for client side
You can serve up any files you want with express static method:
app.use(express.static('public'))
in this case just put all the files you want to serve in folder called public and then you can access it by localhost:8080/Helloworld.txt.
I ended up working around it.
I sent the file name as a header and was thus able to create a replica of the file I wanted to download using the body info and the filenameheader.
I'm trying to use gun in an express/node project, however I want to mount the endpoint as /db. I had hoped the following code would work but keep getting a Route.get() requires callback functions error:
var express = require('express');
var Gun = require('gun');
var app = express();
var port = 8080;
var gun = new Gun({
file: './data.json'
});
// mount the gun db server
app.get('/db', gun.router);
// regular express route
app.get('/', function(req, res) {
res.send('other stuff...');
});
// start the server
app.listen(port, function () {
console.log('Web server listening on port ' + port);
});
Any suggestions?
Doherty!
GUN can be used with express, but it is not an express route. For example, lets first go over a simple gun server mounted with express:
var express = require('express');
var Gun = require('gun');
var app = express();
app.use(Gun.serve).use(express.static(__dirname));
var server = app.listen(80);
Gun({file: 'data.json', web: server});
( https://github.com/amark/gun/blob/master/examples/express.js )
GUN's API is now available in the browser at:
<script src="http://YOURSERVER.com/gun.js"></script>
<script>
var gun = Gun('http://YOURSERVER.com/gun');
gun.get('key').get('hello').put('world!');
gun.get('key').get('hello').on(function(data){ console.log(data) });
</script>
GUN is not available as an express route. For example, this does not work:
http://YOURSERVER.com/data/key/hello?put=world!
Why?
GUN is a realtime database, if you use a REST or CRUD routes with express as its API, then you lose the realtime capabilities. Meaning you would have to write your own custom long-polling implementation, which defeats the point of having an express route.
I understand, but I still want a REST or CRUD API for GUN?
It should not be hard to create an HTTP route that proxies gun. Here is some pseudocode that should help get you started. If you build it, please make it an Open Source module on NPM so others can enjoy it!!!
// this is pseudocode!!!
app.get('/data', (req, res) => {
path(req).val(data => res.send(data))
});
app.put('/data', (req, res) => {
path(req).put(req.param.put, ack => {
res.ack? 0 : res.ack = res.send(ack)
})
});
var path = (req) => {
var ref = gun;
req.path.split('/').forEach(key => ref = ref.get(key));
return ref;
}
Let us know if you build it! As always, the community chatroom is friendly and active. Ask for help there, and ask questions here. Thanks for making this a SO question!
Hi Please see below sample code.
const express = require('express')
const app = express()
var port = process.env.PORT || 3000;
var appmetrics = require('appmetrics');
var monitor = appmetrics.monitor();
appmetrics.enable('http');
appmetrics.enable('request');
monitor.on('request', function (request) {
console.log('request', request);
});
monitor.on('http', function (http) {
console.log('http', http);
});
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(port, function () {
console.log('Example app listening on port 3000!')
})
'
Whenever I fire localhost:3000 from browser. I get 'Hello World!' reply but logs doesn't show any request or http event. Can somebody help me to point out issue.
I am using latest appmetrics version.
Thanks in Advance.
Have you tried putting line 4 (the appmetrics require line) at the top of the code? If it works, please close the issue you raised https://github.com/RuntimeTools/appmetrics/issues/452
I am still learning nodejs and was listening to daniel shiffman's video on how to setup the twitter api and how to get data from it.
Now, the code was working and I was getting back data, but it was all happening in the terminal.
What I wanted to do was to show the twitter data in my browser and wasnt sure how to do that. I tried searching for it, but didnt get much help.
So, I just tried doing whatever I knew and it worked and therefore I am still not sure that the code I have written is the proper way to do this.
I'd love to know if there's a mistake somewhere or If there's some other way I should have done this.
Anyways, here's the code
var http = require('http');
var express = require('express');
var app = express();
var port = 8080; // Use 8080 for local development because you might already have apache running on 80
console.log('The bot is starting');
var Twit = require('twit');
var config = require('./config');
console.log(config);
var T = new Twit(config);
var params ={
q:'spider',
count:5
}
T.get('search/tweets', params, gotData);
function gotData(err, data, response) {
var tweets = data.statuses;
app.get('/',function(req,res){
req=params;
var tweetz='';
for(var i=0;i<tweets.length;i++){
console.log(tweets[i].text+'================================');
tweetz = '<p>'+ tweetz+tweets[i].text+'</p>';
}
res.send(tweetz);
});
}
app.listen(port, function () {
console.log(`app listening on port ${port}!`);
});
The mistake you are doing is declaring app.get inside the callback.
app.get("/", function....) is a route which responds to GET requests which means whenever a user requests for "/", the callback which is the function(req, res) is called.
So the code should be:
app.get("/", function(req, res) {
// User requested for "/" route, now get tweets
T.get('search/tweets', params, function(err, data) {
//Tweets received, now send the tweets to the user
var tweets = data.statuses;
return res.send(tweets);
})
})
Then go to http://localhost:8080/ and it should work.