I am trying to use the debug NPM module in conjuction with my express js app. However, when i try to create the environment variable and run the app, I do not receive any of the debug logs!
var express = require("express");
var chalk = require("chalk");
var debug = require("debug")("app");
var app = express();
app.get("/", function(req, res) {
res.send("Hello from my library app! ");
});
app.listen(3000, function() {
debug(`Listening on port ${chalk.green("3000")}. `);
});
I am running windows and am trying the following command in the terminal inside my project directory:
set DEBUG=* & node app.js
When i execute this command, the site works - but i do not get any logs atall!
Have you tried telling debug to use HTTP instead of app
const debug = require('debug')('http');
Express uses http in the back end and I assume it needs HTTP to be called
Edit:
My mistake the (http) part is only namespace
To fix this I added
debug.enabled = true;
This seemed to fix it
Related
function skipBR() {
location.href = 'boardroom.ejs';
}
here I want to call boardroom.ejs file in different page using function.
The location.href = '/path' is a client side function, in server side is used the Express function res.redirect('/path') as #santhosh has mentioned in the comments.
This would look something like:
terminal:
npm install -s express
your .js file:
const express = require('express');
const app = express();
app.get('/', (req, res) =>
res.redirect('/boardroom.ejs');
});
So i recently created an Account at heroku.com and created a PostgreSQL database. First of all i wanted to test if i could store something into the database (One table was already created without node.js) but for some odd reason the callback function of my dbClient.query never executed. I then realized that the Database does not connect to my code. My password, host, etc. should all be right and i can connect from extern sites but not from my node.js code.
Here´s my code:
var express = require("express");
var pg = require("pg");
var bodyParser = require("body-parser");
var CON_STRING = process.env.DB_CON_STRING;
if (CON_STRING == undefined) {
console.log("Error: Environment variable DB_CON_STRING not set!");
process.exit(1);
}
pg.defaults.ssl = true;
var dbClient = new pg.Client(CON_STRING);
dbClient.connect();
var urlencodedParser = bodyParser.urlencoded({
extended: false
});
var PORT = 3000;
var app = express();
app.set("views", "views");
app.set("view engine", "pug");
app.get("/shoppingitems", function (req, res) {
res.render("shoppingitems")
});
app.post("/shoppingitems", urlencodedParser, function(req, res){
var shoppingItem = req.body.shoppingItem;
dbClient.query("INSERT INTO shoppinglist (title) VALUES ($1)", [shoppingItem], function(dbError, dbResponse){
console.log("function called!");
res.redirect("/shoppingitems");
})
console.log("test");
})
app.listen(PORT, function () {
console.log(`Shopping App listening on Port ${PORT}`);
});
It does not work with other configs of dbClient.query.
You need to set the environment variable on your localhost, depending on your OS.
For Mac & Linux use 'export' keyword in Terminal for YOUR_ENV_VAR, example:
export DB_CON_STRING=postgres://ufohlgoihdgfalr:2fb913jhazsxd541469b972fcac862ddf664620998e87c96787569poiude4ab0b#ec2-34-238-26-109.compute-1.amazonaws.com:5432/d587yhytte32gj
You can check your variable using 'echo' and $ sign in Mac and Linux, for example
echo $DB_CON_STRING
It should give you the string if the variable is set or not.
Note that will be only work for the current session in the Terminal, if you want to keep it and use it for a long time or after closing/opening the terminal then it is better to add it to your .bash_profile. Same way, just make it saved in the /uerMacUser/.bash_profile
For windows you can do it using GUI, for quick access use in 'Run' rundll32.exe sysdm.cpl,EditEnvironmentVariables
Heroku Postgres uses different environment variable named 'DATABASE_URL' so you might want to consider this if you want to deploy on heroku later, otherwise your application will not start on heroku.
I've hosted a nodejs server on localhost generated using Swagger and I'm trying to make API calls to it using Swagger UI again hosted on localhost. The network profile in chrome is showing connection refused everytime I'm making a call because CORS header are not added to the request.
This is my app.js file which was generated using Swagger:
'use strict';
var SwaggerExpress = require('swagger-express-mw');
var app = require('express')();
module.exports = app; // for testing
var config = {
appRoot: __dirname // required config
};
SwaggerExpress.create(config, function(err, swaggerExpress) {
if (err) { throw err; }
// install middleware
swaggerExpress.register(app);
var port = process.env.PORT || 10010;
app.listen(port);
if (swaggerExpress.runner.swagger.paths['/hello']) {
console.log('try this:\ncurl http://127.0.0.1:' + port + '/hello?name=Scott');
}
});
Till now I've tried the following methods and none of them has worked:
Importing cors module from npm:
npm install cors
In app.js
var cors = require('cors');
app.all(cors())
Adding CORS using statements given in enable-cors website:
http://enable-cors.org/server_expressjs.html
Both the above methods have failed for me, what can I try next? I can share more code samples if required.
I guess you have not configure cors properly.
npm install cors
Usage
var cors = require('cors');
app.use(cors());
See more
CORS Support
https://github.com/swagger-api/swagger-ui#cors-support
After thorough researching, I decided to use Bluemix for classifying and recognizing images.
I'm have a starter question on how to begin programming using node.js runtime.
I tried to follow this tutorial. However, that is just snippets of code. How do you run them and see it working in the Bluemix environment?
My progress:
-I started the node.js starter application in Bluemix.
-I added the following code and the app.js looks like this:
/*eslint-env node*/
//--------------------------------------------------------------------------
// node.js starter application for Bluemix
//--------------------------------------------------------------------------
// This application uses express as its web server
// for more info, see: http://expressjs.com
var express = require('express');
// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');
// create a new express server
var app = express();
// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));
// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();
// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {
// print a message when the server starts listening
console.log("server starting on " + appEnv.url);
});
var watson = require('watson-developer-cloud');
var fs = require('fs');
/*var visual_recognition = watson.visual_recognition({
username: '<username>',
password: '<password>',
version: 'v2-beta',
version_date: '2015-12-02'
});*/
var visualRecognition = watson.visual_recognition({
version: 'v3',
api_key: process.env.API_KEY || 'my api key',
version_date: '2015-05-19'
});
var params = {
images_file: fs.createReadStream('./resources/car.png')
};
visualRecognition.classify(params, function(err, res) {
if (err)
console.log(err);
else
console.log(JSON.stringify(res, null, 2));
});
I'm trying to run the code in the Bluemix environment (live edit mode) and not locally. When I hit run the code, the deployment stops and I can't even locate what line of code is making this happen. When I visit the webpage I get the following error:
404 Not Found: Requested route ('myvisualapp.mybluemix.net') does not exist.
I don't understand what's wrong and how to debug the code.
Author level: beginner
You need to 'route' (or at least intercept) the client requests in express. Right now, the request do not have a handler. Use app.get() call for that purpose
Your watson service calls are unbounded to a user request right now. You need to funnel it through a user request.
For example:
app.get('/', function(req, res) {
// invoke watson services
// get the result.
// write back the result through the response object, res
}
You can look at the demo code at https://github.com/watson-developer-cloud/visual-recognition-nodejs and get a good place to start.
Also, from the command line you can see the logs of your application deployed into bluemix using
$ cf logs YOURAPPNAME --recent
where YOURAPPNAME is the name of the application you pushed to bluemix. You can get the name using
$ cf apps
if you forget the name you used (which happens to me all the time).
I have been following the Heroku Stormpath docs to setup a simple Express app. The code from my server.js file is shown below:
'use strict';
var express = require('express');
var pg = require('pg');
var stormpath = require('express-stormpath');
var app = express();
app.use(express.static('public'));
app.use(stormpath.init(app, {
apiKeyFile: '/.stormpath/apiKey.properties',
apiKeyId: process.env.STORMPATH_API_KEY_ID,
apiKeySecret: process.env.STORMPATH_API_KEY_SECRET,
secretKey: process.env.STORMPATH_SECRET_KEY,
application: process.env.STORMPATH_URL,
}));
app.set('port', (process.env.PORT || 5000));
app.listen(app.get('port'), function(){
console.log('Node app is running on port', app.get('port'));
});
Forgive me for being a newbie to Stormpath. I've looked through the Express-Stormpath docs as well, but I continue to receive the following error when running the app locally:
Node app is running on port 5000
events.js:141
throw er; // Unhandled 'error' event
^
Error: API key ID and secret is required.
I have provisioned the Stormpath addon via Heroku, and when running heroku config in the terminal I see that all of the variables passed into stormpath.init are available. Can someone enlighten me as to what I am doing wrong?
if you are running your server app locally, I can guess that you didn't create the environment variables so try this:
$ STORMPATH_API_KEY_ID=123 STORMPATH_API_KEY_SECRET=secret STORMPATH_SECRET_KEY=secret STORMPATH_URL=url node app.js
or you can set the storm values whenever they are empty as in your case:
app.use(stormpath.init(app, {
apiKeyFile: '/.stormpath/apiKey.properties',
apiKeyId: process.env.STORMPATH_API_KEY_ID || 'key',
apiKeySecret: process.env.STORMPATH_API_KEY_SECRET || 'secret',
secretKey: process.env.STORMPATH_SECRET_KEY || 'key',
application: process.env.STORMPATH_URL || 'url'
}));
in either case provide your real stormpath values from your addon at heroku.
This is for anyone coming for a solution to this problem.. You should refer the Getting started steps provided by Stormpath!
For express.js refer this.
This might be what you were missing..
Set the environment variables: UNIX
export STORMPATH_CLIENT_APIKEY_ID=5EFMBEN6N34AU36ENEEGJ9YLY
export STORMPATH_CLIENT_APIKEY_SECRET=iII3MZPC2hJC/yuOXMjaa0/0GcgyeApfPVvWyNmMR1c
export STORMPATH_APPLICATION_HREF=https://api.stormpath.com/v1/applications/7F0kZw0wqcFBNh1dDbWMiU
Set the environment variables: WINDOWS
set STORMPATH_CLIENT_APIKEY_ID=5EFMBEN6N34AU36ENEEGJ9YLY
set STORMPATH_CLIENT_APIKEY_SECRET=iII3MZPC2hJC/yuOXMjaa0/0GcgyeApfPVvWyNmMR1c
set STORMPATH_APPLICATION_HREF=https://api.stormpath.com/v1/applications/7F0kZw0wqcFBNh1dDbWMiU