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.
Related
I am trying to get weather forecast data from API of weatherapi.com but when I parsed the JSON data it show error that unexpected end of json input. I also tried setTimeout function as if it takes times to fetching data but not helpful.
const express = require('express');
const https = require('https');
const bodyParser = require('body-parser');
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended:true}));
app.post("/weather-data",function(req, res){
var city_name = req.body.city_name;
city_name = city_name.toUpperCase();
const key = "4b6f380fa80745beb2c174529222912";
const days = 1;
url = "https://api.weatherapi.com/v1/forecast.json?key="+key+"&q="+city_name;
https.get(url,(response)=>{
console.log(response.statusCode);
const status = response.statusCode;
if(status == 200){
response.on("data",function(data){
const WeatherData = JSON.parse(data);
const region = WeatherData.location.region;
const country = WeatherData.location.country;
console.log("region is "+region+" and country is "+country);
});
}
});
});
Note that response.on("data") event is triggered every time a chunk of data arrives and it can happen multiple times per request (not necessarily all data arrive simultaneously, especially for large payloads).
You should buffer the data and parse it only after all data arrived:
let dataBuffer = '';
response.on("data", function(data) {
dataBuffer += data;
});
response.on("end", function() {
const weatherData = JSON.parse(dataBuffer);
...
...
});
I'm trying to setup a simple login API using node.js/restify. The code below shows a simple route, with nothing but a console.log() statement within it, as I'm just trying to prove I can gain a connection.
var restify = require('restify');
var user = require('./user');
var reference = require('./reference');
var fs = require('fs');
var bodyParser = require('body-parser');
var _= require('lodash');
const server = restify.createServer();
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({extended:false}));
server.use(restify.plugins.fullResponse())
server.use(restify.plugins.bodyParser());
server.use(restify.plugins.queryParser()) server.use(restify.plugins.authorizationParser())
var port = 8080;
server.post('/user/login', (req, res) => {
console.log("---LOGIN ATTEMPT---");
res.status(200);
res.end();
});
Using Postman for testing, I expect to get a statement back in the console, stating "LOGIN ATTEMPT".
Postman freezes with the 'Loading' text and stays like that until it crashes saying 'There was an error connecting to localhost:8080/user/login'. This only occurs when sending JSON data and not when sending form-data, which is where my confusion is occurring. It is acting as if an infinite loop is occurring with JSON data but can not trace where it is happening.
because you are not sending any data back to requesting browser(in this case postman) try returning some response as body
for example use res.send('success')
Trying to get sessions working using Node.js and Express for my personal project. I'm using a MySQL database as my session store, and have installed the following modules:
express
body-parser, to get POST data
mysql, to connect to my DB
cors
express-session
express-mysql-session
bcrypt, to compare POSTed data with DB hashes
I'm sending a POST request containting login info through javascript from a page, which I compare with an hash from the database. If it matches, I create the session for the user. I want to prevent the user from logging in again if it has a session, but it looks like the session cookie isn't being stored. I verified this by looking at req.session, but the user object I created never appears there.
Records in the database are being created: if I login with correct data, a new record is created. I'm not sure if this is supposed to happen but if I login again with the same user it creates a new record.
Here's what I've got:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
var cors = require('cors');
var session = require('express-session');
var MySQLStore = require('express-mysql-session')(session);
var bcrypt = require('bcrypt');
var options = { ... };
var pool = mysql.createPool(options);
var sessionConnection = mysql.createConnection(options);
var sessionStore = new MySQLStore({
expiration: 10800000,
createDatabaseTable: true,
schema: {
tableName: 'USERS_SESSIONS',
columnNames: {
session_id: 'session_id',
expires: 'expires',
data: 'data'
}
}
}, sessionConnection);
// i'll change key & secret later
app.use(session({
key: '69Atu22GZTSyDGW4sf4mMJdJ42436gAs',
secret: '3dCE84rey8R8pHKrVRedgyEjhrqGT5Hz',
store: sessionStore,
resave: false,
saveUninitialized: true
}));
app.use(cors());
...
var router = express.Router();
router.post('/login', function(req, res){
if (req.session.user){
console.log('already logged in');
}else{
// get connection from pool, retrieve user record
// PLAIN is password from request, row.HASH is the record's hash
bcrypt.compare(PLAIN, row.HASH, function(err, match){
// do error handling
// when match = true do this
req.session.user = {
id: row.ID,
nickname: row.NICK,
isAuthed: true
};
res.sendStatus(200); // else send 401
return;
});
}
});
After successfully logging in, I check my session like this:
router.get('/session', function(req, res){
res.json(req.session);
});
And I get the following:
{"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"}}
As you can see there's no user object. I'm not getting any errors and I can't figure out where's the problem.
var cookieParser = require('cookie-parser');
Please add app.use(cookieParser()); before
app.use(session({
key: '69Atu22GZTSyDGW4sf4mMJdJ42436gAs',
secret: '3dCE84rey8R8pHKrVRedgyEjhrqGT5Hz',
store: sessionStore,
resave: false,
saveUninitialized: true
}));
For detailed documentation
https://www.npmjs.com/package/cookie-parser
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;
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'));