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).
Related
I have front-end folder files with react components and front-end css libraries.
In different folder, I have back-end files with server.js routing with mysql connection.
When I enter inputs on the screen, the inputs are not saved to mysql database.
Questions:
In what file, do I connect my front-end with back-end?
What statement should I use to connect my front-end with back-end?
To start Front-end, I used: npm start and To start Back-end, I used: nodemon server.js.
Question: When I connect front-end and back-end, what file should I open so that the front-end talks with the back-end -> both are starting?
Question 1 answer
You can do this a number of ways. I've done this with Serverjs and react in the
following manner.
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const port = 80085;
const app = express();
const token = 'impossiblylongimportanttokenhere';
let nextId = 7;
You'll need to import CORS, a Parser, Express for routing purposes.
Assuming you'll have a login you'll want a authenticator function. Please note this is just for development.
function authenticator(req, res, next) {
const { authorization } = req.headers;
if (authorization === token) {
next();
} else {
res.status(403).json({ error: 'User must be logged in to do that.' });
}
}
You'll probably want to replace that with something more secure once you're don with development.
with app as our router express has several CORS methods to get us started likepostget
Here's an example of one if we had an array called friends and if we wanted to find that friend by ID.
app.get('/api/friends/:id', authenticator, (req, res) => {
const friend = friends.find(f => f.id == req.params.id);
if (friend) {
res.status(200).json(friend);
} else {
res.status(404).send({ msg: 'Friend not found' });
}
});
The best part is that express has a method called listen that will start as soon as we hit NPM RUN on a cli that's parked in the same file location as server.js. Make sure to specify a port that your system isn't already using
app.listen(port, () => {
console.log(`server listening on port ${port}`);
});
Question 2
In order to get connect to Server.js on our side you'll want use axios to make a GET/POST etc. call to whatever route you've made in your server.js above in the example it would be
.post('/api/friends', this.state.addFriend)
The biggest thing is you'll want multiple terminals running in order to have both the backend and the front end running at the same time. Start with backend first.
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
I'm working on rendering the basic starting 'Hello, world' view of my Nodejs project based on the MVC model in this tutorial.
However, I couldn't believe after I wrote down bunches of js scripts, I tested with running the server script with node server.js, I kept getting this error as in the screenshot below:
I thought there was definitely something wrong with my Nodejs package Hapi with the incompatible version, but its version is even updated than the version used in the tutorial.
I checked the code line by line with the one given in the phase of the tutorial, but couldn't find anything wrong. So it should be something wrong in the server code. So what really goes wrong here? See the notes in the server.js code below:
'use strict';
//create all related dependencies
const Hapi = require('hapi');
const Hoek = require('hoek');
const Settings = require('./settings');
//instantiate server object with connection port of Settings
const server = new Hapi.Server();
server.connection({port: Settings.port});
//create a testing route and initiate the HTTP call
server.route(
{
method: 'GET',
path: '/',
handler: (request, reply) => {
reply('Hello, this is the Nodejs project for Dota2Insight');
}
}
);
server.start((err) => {
Hoek.assert(!err, err);
console.log(`Server running at: ${server.info.uri}`);
});
I'm very inexperienced with Nodejs.
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
I've read i can run mocha test in an Express application (nodeJS) with super test and therefore it is not required to run the app in a different terminal session.
Whatever i try it always ends with a connection error.
To configure our continuous integration it is evident the integration and unit test (mocha, supertest, should) should be able to run without the node server is also running
The written tests are to validate our app's internal api end points
Who can explain how to run the tests without running the express server of the app so they can be integrated with for example strider
You need to split out your production code that calls app.listen and make sure that does not get executed during a mocha test run. I put all of my routes and settings code in app/index.js and then have a separate file app/server.js that has just a tiny bit of code to start listening, connect to the database, etc. But most of my application details are configured in app/index.js so I can test them with supertest.
//index.js
var app = require("express")();
app.get("/", function (req, res) {
res.type("text");
res.send("Welcome home");
});
module.exports = app;
//server.js
#!/usr/bin/env node
var app = require("./index");
app.listen(3000);
//index.mocha.js
var app = require("./index");
var request = require("supertest")(app);
var expect = require("expectacle");
describe("the home page", function () {
it("should welome me in plain text", function(done) {
request.get("/")
.expect(200)
.expect("Content-Type", "text/plain; charset=utf-8")
.end(function (error, result) {
expect(error).toBeFalsy();
expect(result.text).toBe("Welcome home");
done();
});
});
});