external api results not loading in node.js using https module - express

whats wrong with my code? its showing no results....although it kinda works when i use google.com as url but in other cases it shows no results*I haven't shared my api key here(appid=)
const express = require('express');
const app = express();
const http = require('http');
app.get("/", function(req, res) {
const url= 'https://api.openweathermap.org/data/2.5/weather?q=london&appid='
http.get(url, function(response){
console.log(response);
// response.on("data", function(data){
// const weatherData = JSON.parse(data);
// const temp = weatherData.main.temp;
// // const weatherDescription = weatherData.weather[0].description;
// res.send(temp)
// })
// res.send('server is sending');
})
})
app.listen(3000, function(req, res){
console.log('Server is alive')
})

Related

authenticate tp express server tunneled through ngrok

I have an express server serving react pages. I am trying to show the work to a client via a ngrok tunnel. But whenever I try to log in at the ngrok URL for my server it fails to connect back to my localhost where the express routes for auth are.
I feel like it's a simple error I'm making. The browser is trying to make a request to the express server at localhost:5000, but there is nothing at localhost on my client's network.
This is my app.js
const createError = require('http-errors');
const express = require('express');
const debug = require('debug')('app');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
require('dotenv').config()
const ensureToken = require('./middleware/ensureToken');
const path = require('path');
const app = express();
const { init } = require('./utils/cron/createCron');
const cors = require('cors')
// Routers
const authRouter = require('./routes/auth')
const botRouter = require('./routes/bot')
const proxyRouter = require('./routes/proxy');
const winstonLogger = require('./utils/log/logger');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
const whiteList = ['http://localhost:3000/', 'http://localhost:3000']
const corsOptions = {
origin: (origin, callback)=>{
if (whiteList.indexOf(origin) !== -1){
callback(null, true)
}else{
callback(new Error('Not Allowed by CORS'))
}
optionsSuccessStatus:200
}
}
// app.use(cors(corsOptions))
app.use(cors({ credentials: true, origin: true }))
app.use(express.static(path.join(__dirname, 'build')));
// Base Routes
app.use('/api/auth', authRouter);
app.use(ensureToken) //Add this before routes that need to be protected ny valid token
app.use('/api/bot', botRouter);
app.use('/api/proxy', proxyRouter);
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "../client/build/index.html"));
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.listen(process.env.PORT, ()=>{
winstonLogger.info(`Listening on ${process.env.PORT}`)
debug(`Listening on ${process.env.PORT}`);
console.log(`Listening on ${process.env.PORT}`);
init()
})
module.exports = app;
Any help is appreciated!!

Connect flash not displaying messages in Pug

I have an application with several routes, and I want to send flash messages of different kinds given the user interaction: either a success or failure message, or in some cases no message. Right now the messages are not displaying and I can't figure out how to get it to work. I'm using Node, Express and Pug.
I have a server.js file, routes.js file, message.pug file, and layout.pug file. Here are my files:
server.js
// init project
const express = require('express');
const app = express();
const bodyparser = require("body-parser");
const flash = require('connect-flash');
const passport = require("passport");
const session = require("express-session");
// http://expressjs.com/en/starter/static-files.html
app.use(express.static("public"));
app.set('view engine', 'pug');
// bodyparser middleware
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
// express-session middleware
app.use(session({
secret: process.env.SECRET,
resave: true,
saveUninitialized: true
}));
// express-messages middleware
app.use(flash());
app.use((req, res, next) => {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.use(express.json());
// import passport-config file
require("./passport-config")(passport);
// passport middleware
app.use(passport.initialize());
app.use(passport.session());
const routes = require('./routes.js');
routes(app);
// listen for requests :)
const listener = app.listen(process.env.PORT, () => {
console.log('Your app is listening on port ' + listener.address().port);
});
routes.js
app.get('/', (req, res) => {
req.flash("success", "your flash messages are working");
res.redirect("/admin");
});
app.get("/admin", (req, res) => {
res.render(process.cwd() + '/views/pug/admin');
});
message.pug
.messages
each type in Object.keys(messages)
each message in messages[type]
div(class="alert alert-" + type) #{ message }
// expected output
// div(class="alert alert-success") your flash messages are working
layout.pug
div.col-10.ml-sm-auto.px-4
!= messages('message', locals)
Since I had only two types of messages I was sending -- success or error -- I got rid of my messages.pug file and used the following code, which works.
server.js
// init project
const express = require('express');
const app = express();
const bodyparser = require("body-parser");
const flash = require('connect-flash');
const passport = require("passport");
const session = require("express-session");
// http://expressjs.com/en/starter/static-files.html
app.use(express.static("public"));
app.set('view engine', 'pug');
// bodyparser middleware
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
// express-session middleware
app.use(session({
secret: process.env.SECRET,
resave: true,
saveUninitialized: true
}));
// express-messages middleware THIS IS WHAT I CHANGED
app.use(flash());
app.use((req, res, next) => {
res.locals.errors = req.flash("error");
res.locals.successes = req.flash("success");
next();
});
app.use(express.json());
// import passport-config file
require("./passport-config")(passport);
// passport middleware
app.use(passport.initialize());
app.use(passport.session());
const routes = require('./routes.js');
routes(app);
// listen for requests :)
const listener = app.listen(process.env.PORT, () => {
console.log('Your app is listening on port ' + listener.address().port);
});
routes.js (the same as before)
app.get('/', (req, res) => {
req.flash("success", "your flash messages are working");
res.redirect("/admin");
});
app.get("/admin", (req, res) => {
res.render(process.cwd() + '/views/pug/admin');
});
Then in layout, I use the following:
div.col-10.ml-sm-auto.px-4
if successes
for success in successes
div.alert.alert-success #{ success }
if errors
for error, i in errors
div.alert.alert-danger #{ error }
This works for displaying a message in a redirect.
Note: If you want to display a message directly (via res.render()), you have to pass it to the render method directly like this:
app.get('/admin', (req, res) => {
req.flash("success", "flash message for a render method");
res.render("/admin", { successes: req.flash("success") });
});

routes in exported router not available in app

I'm trying to export a router 'Accounts' to use in my app. The 'Accounts' router has the paths '/login' (POST), '/register'(POST), 'login' (GET), and '/logout' (POST). In my index app I am using the router with the path '/account'. So the paths should be:
/account/login (POST)
/account/login (GET)
/account/register(POST)
/account/logout (GET)
But when I call these paths they aren't found by the app:
How do I get the paths in the 'accounts.js' router to work in the 'index.js' app?
My file structure is like this:
my account.js file looks like this:
const express = require('express');
const passport = require('passport');
const Account = require('../models/Account');
const Branch = require('../models/Branch')
const router = express.Router({mergeParams: true});
const registerAccount = (req, res, next) => {
//register the account
};
const createUser = (req,res) => {
//create a user in another db
}
router.post('/register',
[registerAccount, createUser]);
router.get('/login', function(req, res) {
res.json(user);
});
router.post('/login', passport.authenticate('local', { successRedirect: '/',
failureRedirect: 'account/login' }));
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
});
module.exports=router;
and my index.js looks like this:
// index.js
var express = require("express");
var bodyParser = require("body-parser");
var jwt = require("jwt-simple");
var auth = require("../auth/auth.js")();
var users = require("./users.js");
var cfg = require("../config.js");
const accountController = require('./account');
var app = express();
app.use(bodyParser.json());
app.use(auth.initialize());
app.use('/account',accountController);
app.get("/", function(req, res) {
res.json({
status: "My API is alive!"
});
});
app.post("/token", function(req, res) {
//some token stuff that doesn't matter here
});
module.exports = app;
For starters, you don't pass an array to a router.post(), so change this:
router.post('/register', [registerAccount, createUser]);
to this:
router.post('/register', registerAccount, createUser);
And make sure that registerAccount calls next() when it's done and wants createUser() to get called.
In the doc, for this syntax:
app.post(path, callback [, callback ...])
the brackets in [, callback] mean that parameter is optional. The brackets are not supposed to be used.

send serial port data to front-end with express & node

I want to send serial port data to a browser UI with express. So far my code looks like this:
var SerialPort = require("serialport");
var serialport = new SerialPort("/dev/cu.usbmodem1421");
var express = require('express');
var app = express();
var datenFromA;
serialport.on('open', function(){
console.log('Serial Port Opend');
serialport.on('data', function(data){
datenFromA = data[0];
console.log(datenFromA);
});
});
app.get('/', function (req, res) {
res.send('Hello World')
})
app.listen(3000);
Instead of the 'Hello World' I want to send the value of variable datenFromA to the browser. Any ideas how to pass the value to the app.get function?
Thanks in advance.
Essentially you need to wait until you receive an event. Quick dirty example given below:
const SerialPort = require("serialport");
const serialport = new SerialPort("/dev/cu.usbmodem1421");
const express = require('express');
const app = express();
// Only need to do this once.
serialport.on('open', () => console.log('Serial Port Opend'));
app.get('/', async (req, res) => {
const promise = new Promise((resolve, reject) => {
serialport.on('data', (data, err) => {
if (err) {
reject(err);
return;
}
resolve(data[0]);
});
})
const data = await promise;
res.json(data);
})
app.listen(3000);

Express.js - routes wont work if they have multiple / - 404 error

GET /user/me - sends back 404 (resource not found)
If I change the second '/' to a '_' (i.e GET users_me), then it works.
I have two questions:
1) How to fix it so I can use 'GET /user/me'?
2) It works with an underscore so is there any advantage to using the slash vs. the underscore?
///////////Code
require('./config/config');
const _ = require('lodash');
const express = require('express');
const bodyParser = require('body-parser');
const {ObjectID} = require('mongodb');
//const multer = require('multer');
//const router = express.Router();
var renameKeys = require('rename-keys');
var {mongoose} = require('./db/mongoose');
//var {Todo} = require('./models/todo');
var {User} = require('./models/user');
var {authenticate} = require('./middleware/authenticate');
var app = express();
const port = process.env.PORT;
app.use(bodyParser.json());
// GET users/me
app.get('/users_me', authenticate, (req, res) => {
res.send(req.user);
});
// POST /users -- signing up a new user [how will this handle logging in instead of signing up?]
app.post('/users', (req, res) => {
var body = _.pick(req.body, ['email', 'password']);
var user = new User(body);
user.save().then(() => {
return user.generateAuthToken();
}).then((token) => {
res.header('x-auth', token).send(user);
}).catch((e) => {
res.status(400).send(e);
})
});
app.listen(port, () => {
console.log(`Started up at port ${port}`);
});
module.exports = {app};
First question:
Just change
app.get('/users_me', authenticate, (req, res) => {
res.send(req.user);
});
to
app.get('/users/:me', authenticate, (req, res) => {
res.send(req.user);
});
Then make a Get request:
somehost:someport/users/myusername
Second question:
Routing works just like a file-system:
/path/subpath/
So you can't use an underscore to substitute a slash '/'
INFO: You could pass the id or name (depends on your logic) of the user in the URL of your GET-request:
GET request (in this case to localhost with port 3000):
localhost:3000/users/getuserbyid/20
route:
router.get('/getuserbyid/:id', .....
Hope that helps ;)