access to public folder is giving me an error - node.js

I am new to Nodejs and I am following a course on Pluralsight for Nodejs using express.
I have the following code:
var express = require('express');
var app = express();
var port = 5000;
app.use(express.static('public'));
app.get('/', function (req, res) {
res.send('Hello World');
});
app.get('/books', function (req, res) {
res.send('Hello Books');
});
app.listen(port, function (err) {
console.log('running server on port ' + port);
});
And then from the command line I run the following:
$ npm start
This is my json file:
{
"name": "library",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.14.0"
}
}
Now the problem I am having is that when from my browser I put: localhost:5000 everything looks fine. I see my Hello World text. But when I am trying to go to a folder under the public such as localhost:5000/css/style.css I get the following error message.
Cannot GET /css/style.css
And here is my folder structure

If you want:
localhost:5000/css/style.css
to be served by:
app.use(express.static('public'));
Then, you need to make sure that style.css is in:
public/css/style.css
where public/css/style.css is evaluated relative to the current working directory.
You don't disclose your file hierarchy, but if localhost:5000/css/style.css isn't working, then apparently style.css isn't located properly in public/css/style.css or your public directory isn't in the proper place.
app.use(express.static('public')); tells express to look for requested files relative to the public directory. So a request for /css/style.css will be looked for at public/css/style.css.
Also, app.use(express.static('public')); assumes that the public directory you want it to look in is relative to the working directory when the app.use() statement is run so you need to either make sure that is also correct or you need to put an absolute path in the express.static() statement so you don't depend on the current working directory.

Related

Server return error 503 after load NodeJS files

First time I´m setting a server to host a PWA. After load basic NodeJS file I am facing problem to see the picture under the images/user folder.
Error -> Cannot GET /images/user/default_user_pic.png
Folder structure
Public
|-index.html
|-node_modules
|-images
|-user
| |-default_user_pic.png
|-channel
NodeJs
var express = require('express');
var app = express();
const path = require('path')
app.use(express.static(path.join(__dirname + '/public')));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
var port = 3000;
app.listen(port);
console.log('Umbler - Express server started on port %s', port);
package.json
{
"name": "temporarysite",
"version": "1.0.0",
"description": "Nodejs temporary site",
"author": "test",
"main": "app.js",
"scripts": {
"start": "node app"
},
"dependencies": {
"express": "4.x.x"
}
}

Express-subdomain not seeing route

I am using the example setup from the https://www.npmjs.com/package/express-subdomain package. However, when I try api.localhost:3000 in a browser it throws an error: "Cannot GET /"
How can I get api.localhost:3000 running? I would consider other solutions, not just ones using express-subdomain as long as you don't have to type in the fqdn in the setup.
app.js:
var subdomain = require('express-subdomain');
var express = require('express');
var app = express();
// *** Code examples below go here! ***
var router = express.Router();
//api specific routes
router.get('/', function(req, res) {
res.send('Welcome to our API!');
});
router.get('/users', function(req, res) {
res.json([
{ name: "Brian" }
]);
});
app.use(subdomain('api', router));
app.listen(3000);
package.json:
{
"name": "auth_manager",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.3",
"express-subdomain": "^1.0.5"
}
}
I think that the API is alive at http://api.example.com/ and not in the api.localhost:3000. However if you want to run them locally I suggest that you follow https://www.npmjs.com/package/express-subdomain#developing-locally
If you plan to use this middleware while developing locally, you have to ensure that your subdomain is listed in your hosts file. Refer here.
On MacOS:
Adjust host file to forward requests from url:
sudo nano /etc/hosts
127.0.0.1 myapp.dev
127.0.0.1 api.myapp.dev
Clear cache:
sudo killall -HUP mDNSResponder
In express:
app.use(subdomain('api', router));
Any authentication middleware needs to be adjusted to authenticate api.myapp.dev not localhost
In Chrome you can use the api.myapp.dev url
If you are using SSL (https) and have a self signed cert: Chrome usually blocks the hostfile URL if it is not localhost. Then, you need to click anywhere in the Chrome window and literally type in thisisunsafe and it will let you through. Refer to this ticket.

How to deploy node app on openshift and run it?

Just created a very simple hello world app using node:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'
app.listen(server_port, server_ip_address, function () {
console.log( "Listening on " + server_ip_address + ", port " + server_port )
});
and it works as it is expected in my local machine,
put that on github and deployed it on openshift, pod created and server running fine:
but when I browse the route which I could find it in Application>>routes menu it says:
Application is not available
The application is currently not serving requests at this endpoint. It may not have been started or is still starting.
I guess I'm using the latest version of openshift since just created an account.
I'm expecting it to show me the Hello world!
update1:
here is my package.json:
{
"name": "npmtest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.2"
}
}
Your application server IP address needs to be 0.0.0.0. So you either specify an environment variable for that, or hard code it.
have you configure main file in package.json
and maybe you need to get port dynamically from the environment variables check below link for openshift sample
https://github.com/openshift/nodejs-ex

Fb developer issue - 'URL couldn't be validated. Response does not match expected challenge'

I've launched a Heroku application using the following files:-
app.js
'use strict'
const express = require('express')
const bodyParser = require('body-parser')
const request = require('request')
const app = express()
app.set('port', (process.env.PORT || 5000))
// Process application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}))
// Process application/json
app.use(bodyParser.json())
// Index route
app.get('/', function (req, res) {
res.send("Hello world, I seem to be working")
})
// for Facebook verification
app.get('/webhook', function (req, res) {
if (req.query['hub.verify_token'] === 'test-token') {
res.send(req.query['hub.challenge']);
} else {
res.send('Error, wrong validation token');
}
})
// Spin up the server
app.listen(app.get('port'), function() {
console.log('running on port', app.get('port'))
})
.gitignore
node_modules
package.json
{
"name": "heroku-node-practice",
"version": "1.0.0",
"description": "New bot",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js"
},
"author": "Paigal",
"license": "ISC",
"dependencies": {
"body-parser": "^1.17.1",
"express": "^4.15.2",
"foobar": "^1.1.0",
"mongoose": "^4.9.8",
"request": "^2.81.0"
}
}
Procfile
web: node app.js
I installed node.js dependencies using the command: npm install express request body-parser --save
After git push heroku master, the application launches correctly.
However, when trying to set up a webhook in fb developer, the error is 'URL couldn't be validated. Response does not match expected challenge' then gives the different responses to the challenge. That is, my URL responds with "Hello world, I seem to be working" instead of numerical key.
Would greatly appreciate your help!
You need to point FB to the route that has the verify function within it. You are currently pointing FB to the site root index '/' it seems.
Change the FB webhook url in the app settings to https://YOUR_DOMAIN.com/webhook and the verification will be complete. FB will then send whatever events you subscribe to to your '/webhook' route.
If this doesn't work, notice you have hardcoded your verify token here as test-token:
...
if (req.query['hub.verify_token'] === 'test-token') { ...
This will only complete the challenge if 'test-token' is what you set your webhook verification token to. A better way to do this imo would be the following:
...
if (req.query['hub.verify_token'] === process.env.VERIFY_TOKEN ) { ...
In the above example you must pass in the verify token you choose for your webhook when running your server, before you try to verify the webhook.
In your heroku dashboard, add VERIFY_TOKEN with your token as the value to your config variables. This will make the verify token available without hardcoding.

Openshift node app error when restarting

I have a node/socket.io chat app hosted on openshift, and while it starts correctly if i ssh into the server and do "node main.js" (where main.js is the server script that starts the chat), I can't start the app on the server by web interface, where it would go on automatically; If i just start the app by ssh, it would stop working as soon as i exit the terminal.
I get this error when starting the app by the web interface:
Starting Node.js application...
Application is already stopped.
Warning! Could not start Node.js application!
Failed to execute: 'control restart' for /var/lib/openshift/57003fbe7628e1491d00011e/nodejs
In case it's relevant, my package.json file is
{
"name": "rainychat",
"version": "1.0.0",
"description": "rainychat, my chat app",
"main": "main.js",
"dependencies": {
"express": "^4.13.4",
"socket.io": "^1.4.5",
"validator": "^5.1.0"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "JG",
"license": "ISC"
}
And here you can see the files of the app by ftp:
I can't decode what that error means...
My main.js code
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function (req, res) {
res.sendFile(__dirname + '/chat.html'); // /home/redadmin/public_html/rainychat.com
console.log('enviado');
});
app.set('port', process.env.OPENSHIFT_NODEJS_PORT || 8080);
app.set('ip', process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1');
http.listen(app.get('port'), app.get('ip'), function () {
console.log('Listening on port ' + app.get('port'));
});
//... More code
If you're creating a new Node project, start with npm init to create the package.json file. You can add the --auto option to give it safe defaults.
Remember, the JSON file must be valid JSON, so test it with jsonlint or a tool like an online validator.
Any dependencies your project has should be spelled out in the package file. This is done automatically with things like npm install express --save.

Resources