Express: sending JSON file as a response - json

I am new to express. I have made a simple react front-end with express backend using express generators and currently, this is the way I am sending JSON data:-
var express = require("express");
var router = express.Router();
router.get("/", function(req, res, next) {
var jsonData = {"name": "manav"};
res.json(jsonData);
});
module.exports = router;
but how can I send data from a JSON file instead? I tried creating a JSON file in the same directory and sending it like res.json('./jsonFile'); but it doesn't work. Could someone help me out please?

You can do like this :
var hoteljsonFile = require("../data/hotel-data.json"); // path of your json file
router.get("/", function(req, res, next) {
res.json(hoteljsonFile);
});

Try in your code like following to read json file
var fs = require('fs');
var path = require('path')
var usersFilePath = path.join(__dirname, 'users.min.json');
apiRouter.get('/users', function(req, res){
var readable = fs.createReadStream(usersFilePath);
readable.pipe(res);
});

Related

Intermittent Response "Unauthenticated requests are not allowed" in node express

Here is the code
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.listen(3000,function(){
console.log("server is running at port 3000");
});
app.get("/",function(req,res){
res.sendFile(__dirname + "/index.html");
});
app.post("/",function(req,res){
console.log(req.body.fiat);
res.send("Your currency is " + req.body.fiat);
// res.send("Your price is "+ price);
});
request("https://apiv2.bitcoinaverage.com/indices/global/ticker/BTCUSD",function(error, response, body){
var data = JSON.parse(body);
var price = data.last;
console.log(price);
});
When I run the above code, sometime I get the Unauthenticated requests are not allowed error and sometime I get the required output like this,
server is running at port 3000
11539.26
Why is it happening, what might be the reason behind this?
You should go through bitcoin average documentation, As you have mentioned you are following any tutorial, maybe, that tutor will not be revealing his key for some reasons.

Uploading image from discord.js bot to my website

I want to use message.attachments to get images from that and upload those to my website (not on localhost). How would i do that?
I already have a working upload form on my website, but how would i do it from a discord.js bot?
According to the discord.js docs, each attachment has a URL property. You can use this to get the image and upload it.
Example code:
const URLsToFetch = [];
const attachments = message.attachments.array();
for(let i = 0;i<attachments.length;++i){
URLsToFetch.push(attachments[i].url);
}
This would get all the attachment URLs, which you can use http, request, or some other similar module to download it and then write it to wherever you put your uploads:
const http = require("http");
const https = require("https");
const {URL} = require("url");
const fs = require("fs");
for(let url of URLsToFetch){
const uri = new URL(url);
const protocol = uri.protocol;
let proto = http;
if(protocol === "https:"){
proto = https;
}
proto.get(uri,response=>{
const chunks = [];
response.on("data",chunk={
chunks.push(chunk);
});
response.on("end",()=>{
const file = Buffer.concat(chunks);
fs.writeFile("path/to/filename",file,err=>{
if(err){throw err} // error
// successfully wrote file
});
});
});
}

scope integrating mongo in a node/express file

I am starting with Mongo db. I want to insert two variables into mongo. So, in the same file
1.- I define the two variables
2.- I create a function that returns a JSON format object with the two variables
3.- I create an app in Express to fill the values of the two variables and send them out as well
4.- I connected to Mongo and insert the JSON object creating a collection and passing in the first argument a call to the function that returns the JSON object with two arguments that are the two variables.
RESULT CHECKING IN THE CONSOLE:
1.- The connection is correct
2.- There is a JSON object inserted but empty
I think I have a problem of scopes.How would it be the right sequence?
// Express files
var express = require('express');
var app = express();
// Mongo files
var mongodb=require("mongodb")
var MongoClient = mongodb.MongoClient;
var MONGODB_URI="mongodb://user:psswd#00000.mlab.com:00000/"
// Variables
var one;
var two;
// JSON object to insert in mongo
var doc=function(one,two){
return{
"one":one,
"two": two
}
}
// App in Express
app.get("new/:which",function(req,res){
one=req.params.which
var randomNum=Math.round(Math.random()*10000)
two=req.headers["x-forwarded-host"]+("/")+randomNum.toString()
res.end(JSON.stringify(doc(one,two)))
})
// Mongo connection and insertion of JSON object
MongoClient.connect(MONGODB_URI,function(err,db){
if (err) {
console.log('Unable to connect to the mongoDB server.
Error:', err);
} else {
console.log('Connection established to', MONGODB_URI);
}
var collection=db.collection("url")
collection.insert(doc(one,two),function(){
if(err) throw err
console.log(JSON.stringify(doc(one,two)))
db.close()
})
})
// Express files
var express = require('express');
var app = express();
//mongoose files
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
mongoose.connect('mongodb://user:psswd#00000.mlab.com:00000/'), {
useMongoClient: true,
});
//Define the document schema
var Schema = new mongoose.Schema({
one: {
type: String, //or maybe Number
required: true
},
two: {
type: String,
required: true
},
});
var Model = mongoose.model('model', Schema);
app.get("/new/:which",function(req,res){
one=req.params.which
var randomNum=Math.round(Math.random()*10000)
two=req.headers["x-forwarded-host"]+ ("/")+randomNum.toString();
var new_doc = new Model({
one: one,
two: two
});
new_doc.save(err=>{
err ? res.send(err) : res.send('added!');
});
});
I recommend to use mongoose npm package for working with mongo
You can split the code into modules for more comfortability
I found the answer to the question of the scopes in a freecourse for Node developers in MongoDB University showing how to put all together Mongo University
The sequence is the following:
//Dependencies
var express = require('express');
var app = express();
var mongodb=require("mongodb")
var MongoClient = mongodb.MongoClient;
var MONGODB_URI
="mongodb://<user>:<psswd>#000000.mlab.com:41358"
// Connection to mongo
MongoClient.connect(MONGODB_URI,function(err,db){
app.use("/new/:which",function(req,res){
var one=req.params.which
var two=req.headers["x-forwarded-host"]+"/"+randomNum
// Insertion of documents
db.collection("url").insertOne({"one":one,
"two":two})
res.send({"one":one,"two":two})
})
var listener = app.listen(8000)
}
So, the app need to be within the scope of the mongo connection and the collection methods within the scope of the app.
At the same level that the app will be the port.
The documents inserted in the database and the result send it out to the client as well.

Scraping Node.js: Getting text from H2 header

Ok so for fun I decided to scrape all the users who go to my college who are signed up on the website moodle.
This is the program I made with Node.js and cheerio that scrapes the site, but I can not seem to get the text that is inside the H2 tag.
This is the website I am scraping from, http://moodle.ramapo.edu/user/profile.php?id=2101
All I need to do is just change the ID number and it loops through every student.
var request = require('request'),
cheerio = require('cheerio');
urls = [];
//For just single page, eventually will loop through each page.
request('http://moodle.ramapo.edu/user/profile.php?id=2101', function(err, resp, body){
if (!err && resp.statusCode == 200) {
var $ = cheerio.load(body);
$('h2.main', '#yui_3_9_1_2_1410303448188_167').each(function(){
//Not sure how to retrieve just the text name of person
});
console.log(urls);
};
});
How do I just select the text inside the H2 tag so that I can log all of them to my console?
That's not the way I'd go about it. Below is a code snippet that should help you out, all you'll need to do is wrap it in a loop and iterate through the urls you want to scrape. I'd also suggest you check out this tutorial Scraping the Web With Node.js
var express = require('express');
var request = require('request');
var cheerio = require('cheerio');
var app = express();
app.get('/scrape', function(req, res){
url = 'http://moodle.ramapo.edu/user/profile.php?id=2101';
request(url, function(error, response, html){
if(!error){
var $ = cheerio.load(html);
var name;
$('.main').filter(function(){
var data = $(this);
name = data.text();
console.log("name = " + name);
})
}
res.send('Check your console!')
})
})
app.listen('8081')
exports = module.exports = app;

Cannot GET error while returning response

I am creating a script using node.js,fbgraph api and express framework. I POST access_token of user from a page index.html on nodejs server. I am able to retrieve the access_token and I used the fbgraph api to retrieve further user info. But when i try to send the response Json object i am getting this error Cannot GET /.
Here are my code , I am not able to understand where is problem coming , everything seems to work. I checked other questions also , they are not helpful in my case, I dont need to show any template. I only want to return response.
NOTE: In my project folder file structure s like this :-
node_modules
app.js
package.json
CODE: app.js
var bodyParser = require('body-parser');
var express = require('express');
var graph = require('fbgraph');
var app = express();
app.use(bodyParser());
//Retrieve POST data
app.post('/', function(req, res) {
// console.log(req.body.access_token);
var access_token = req.body.access_token;
//set access token
graph.setAccessToken(access_token);
//Graph Api request
graph.get("/me?access_token="+access_token, function(err, b_res) {
// console.log(b_res)
var name = b_res.name;
var id = b_res.id;
var profileUrl = b_res.link;
//Retrieve profile url
graph.get("/"+id+"/?fields=picture", function(err, g_res) {
//JSON object to be returned
var userObj = {
"name": name,
"id": id,
"profilerl": profileUrl,
"picurl": g_res.picture.data.url
};
console.log(userObj);
res.json(userObj);
//res.send(userObj);
});
});
});
app.use(express.static(__dirname + '/'));
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'));
As discussed in above comments you can perform db operations here in the same page using userObj attributes in where clause or whatever other operation you want and then pass db returned object in the view like this
var bodyParser = require('body-parser');
var express = require('express');
var graph = require('fbgraph');
var app = express();
app.use(bodyParser());
//Retrieve POST data
app.post('/', function(req, res) {
// console.log(req.body.access_token);
var access_token = req.body.access_token;
//set access token
graph.setAccessToken(access_token);
//Graph Api request
graph.get("/me?access_token="+access_token, function(err, b_res) {
// console.log(b_res)
var name = b_res.name;
var id = b_res.id;
var profileUrl = b_res.link;
//Retrieve profile url
graph.get("/"+id+"/?fields=picture", function(err, g_res) {
//JSON object to be returned
var userObj = {
"name": name,
"id": id,
"profilerl": profileUrl,
"picurl": g_res.picture.data.url
};
console.log(userObj);
//res.json(userObj);
//res.send(userObj);
//perform db operation using userObj and when you get the returned object from db pass it to the view. Let say dataAfterDbOpeations is the returned object of ur query
res.render('views/index', {data: dataAfterDbOpeations})
});
});
});
app.use(express.static(__dirname + '/'));
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'));