404 Not Found: Requested route ('theo-larissa.mybluemix.net') does not exist - javascript

I am new in Bluemix. So far I created web app,got its code and run this app in localhost. Everything works good. The app uses AngularJs and json-server. Later on I will Node.js too. To run it I use 'json-server --watch db.json'. The json file contains various json arrays and objects. And this is my list of links.
http://localhost:3000/news
http://localhost:3000/events
http://localhost:3000/city
http://localhost:3000/administration
http://localhost:3000/deputy_mayors
http://localhost:3000/alcazar_park
http://localhost:3000/feedback
My guess is that all those links should be changed to a live route instead of using localhost. In my dashboard I can see the name's app the route(theo-larissa.mybluemix.net) and it's state with is stopped. Now when I am trying to start the app,I get this message
404 Not Found: Requested route ('theo-larissa.mybluemix.net') does not exist.
Any ideas how to fix this?
Thanks in advance,
Theo.

What do your console logs for theo-larissa.mybluemix.net show? One of the really common deployment mistakes is to leave the port hard-coded in your application when you deploy it to Bluemix. You can't do that; you have to allow Bluemix to specify the port your application will use. You would do that, for example, by encoding something like the following when you create the server:
var server = app.listen(app.get('port'), function()
{console.log('Listening on port %d', server.address().port);});
If you wanted to make this fully automated, you could include code like the following:
app.set('port', appEnv.port);
app.set('appName', 'theo-larissa');
if (cfenv.getAppEnv().isLocal == true)
{http.createServer(app).listen(app.get('port'),
function(req, res) {console.log(app.get('appName')+' is listening locally on port: ' + app.get('port'));});
}
else
{
var server = app.listen(app.get('port'), function() {console.log('Listening on port %d', server.address().port);});
}

app.set('port', appEnv.port);
app.set('appName', 'theo-larissa');
if (cfenv.getAppEnv().isLocal == true)
{http.createServer(app).listen(app.get('port'),
function(req, res) {console.log(app.get('appName')+' is listening locally on port: ' + app.get('port'));});
}
else
{
var server = app.listen(app.get('port'), function() {console.log('Listening on port %d', server.address().port);});
}

Related

Unable to connect to socket - Vanilla JS to node.js

I am trying to work with socket.io, however I am unable to establish a connection between my client (Vanilla HTML/JS) and my server (node.js).
Server code:
const express = require('express');
var cors = require('cors');
const app = express();
app.use(cors())
app.use(express.json());
app.use(express.urlencoded());
var server = app.listen(3001, () => console.log('Listening on port 3001!'));
const io = require('socket.io')(server)
io.on('connection', (socket) => {
console.log("A user connected");
socket.on('disconnect', () => {
console.log("user disconnected")
})
})
I also have several endpoints and functions that are exposed in the same file, though they didn't seem relevant (as far as I know), so I didn't include them here, but can if needed.
HTML:
<head>
<script src="https://cdn.jsdelivr.net/npm/socket.io-client#2/dist/socket.io.js"></script>
<script src="../scripts/index.js"></script>
</head>
index.js:
window.onload = () => {
var socket = io("http://localhost:3001")
socket.on('connect', () => {
console.log("Connected")
console.log(socket.connected)
})
socket.on('test', () => {
console.log("In test socket on")
})
}
I don't seem to be getting any errors thrown in the console or anything, and am not sure where the issue is coming from.
I had a similar issue. I solved it by specifying the origin on cors. Don't just allow all origins through the cors. Instead of app.use(cors()) , use app.use(cors({ credentials: true, origin: 'http://localhost:8080', optionsSuccessStatus: 200 })) or whatever your front end server port is. socket.io also has an option to set origin when initializing. Try this. const io = require('socket.io')(server, { origins: '*:*'});
So as it turns out, the configuration I had for both the client and the server were ok, however it seems as though the issue was with the version of socket.io that I was using. The version I was using was 3.0.3, however when rolling it back to 1.7.4, the setup had worked and I was able to successfully connect to the socket. This isn't an ideal situation by any means, I believe with version 3, the configuration has to be modified. As a quick, temporary fix, this may help, though of course this is by no means an ideal, production-level solution.
I had the same problem. And all i did was let Express know where my static files were.
With:
app.use(express.static(__dirname + '/public')) //Make sure you set here you actual folder
(in my case it was "/public")
I'm using the CDN provided by Socket.io docs:
<script src="https://cdn.socket.io/3.1.3/socket.io.min.js" integrity="sha384-cPwlPLvBTa3sKAgddT6krw0cJat7egBga3DJepJyrLl4Q9/5WLra3rrnMcyTyOnh" crossorigin="anonymous"></script>.
Also i'm declaring the CDN at the end of the file before the closing body tag before my actual JS script containing the implementation.
Also i'm using res.sendFile(*insert here template path*) for example res.sendFile(__dirname + '/public/templates/index.html').

Node Segmentation Fault for any node command with very basic code

Why am I getting a segmentation fault error whenever I type in any node commands?
A bit of background information: I'm trying to deploy any basic demo node app (in GoDaddy's shared hosting) following these instructions (from the comment from user called 'x.g.'). I do everything and get to the very last instruction (number 5) where it states to type node app.js & and I get the following response in the terminal:
[1] 326516
If I type node app.js without the ampersand & I get this error:
Segmentation fault
Does anyone know why this happens and how to fix it? I basically have (as per the instructions) an app.js with this simple code:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('NodeJS server running on Shared Hosting\n');
});
server.listen(port, hostname, () => {
console.log('Server running at http://${hostname}:${port}/');
});
Also, whenever I type anything like node, npm or node-v it also states the Segmentation fault error. Any help would be much appreciated!
Update: any ideas anyone?

proxy node request to new port and act like reverse proxy

I need to create an application that proxies a request from port A to Port B.
For instance if a user connects on port 3000 he will be routed (under the hood) to port 3001, therefore the "original" application will run on port 3001 but in the client (browser) the user will put port 3000.
Not redirect...
http://example.com:3000/foo/bar
A new server will be created which listens to port 3001 and all the call are actually to port 3000 running with the new server and new port.
Since port 3000 is actually occupied,by my reverse proxy app? how should I test it...
Is there a way to test this to verify that this is working,e.g. by unit testing?
I've found this module https://github.com/nodejitsu/node-http-proxy which might be able to help.
Straight from the node-http-proxy docs, this is quite simple. You can test it simply by making an HTTP request to port 3000 -- if you get the same response as you do on port 3001, it's working:
var http = require('http'),
httpProxy = require('http-proxy');
//
// Create a proxy server with custom application logic
//
var proxy = httpProxy.createProxyServer({});
var server = http.createServer(function(req, res) {
// You can define here your custom logic to handle the request
// and then proxy the request.
proxy.web(req, res, {
// Your real Node app
target: 'http://127.0.0.1:3001'
});
});
console.log("proxy listening on port 3000")
server.listen(3000);
I highly recommend you write a suite of integration tests using some thing like mocha for your project as well - in this way, you can run your tests both against your server directly and against your proxy. If tests pass against both, then you can be assured your proxy is behaving as expected.
A unit test using mocha and should.js would look something like this:
var should = require('should');
describe('server', function() {
it('should respond', function(done) {
// ^ optional synchronous callback
request.get({
url: "http://locahost:3000"
// ^ Port of your proxy
}, function(e, r, body) {
if (e)
throw new Error(e);
body.result.should.equal("It works!");
done(); // call the optional synchronous callback
});
});
});
You then simply run your test (once Mocha is installed):
$ mocha path/to/your/test.js
You can either verify that this is working by adding the following
to the proxy request (as described in Remus answer )
proxy.on('proxyReq', function (proxyReq, req, res, options) {
res.setHeader('App-Proxy', 'proxy');
});
In this way you can verify that your "original" call is working against the new server proxy and even provide the ability to create a UT,in addition you can use the changeOrigin:true property...

How do I view my JSON data in a browser from my node.js VM Instance?

I currently have Google cloud Compute engine running nodejs that is connected to a Google Cloud SQL witch takes data from MySQL workbench. This is my server.js file that I run with 'node'
var gcloud = require("gcloud");
var express = require("express");
var http = require('http');
var mysql = require("mysql");
var connection = mysql.createConnection({
port: "3306",
host : "173.194.87.72",
user : "root",
password : "****",
database : "scripto_5_k"
});
var app = express();
/* Connection to Database */
connection.connect(function(error){
if(error)
{
console.log("Problem with MySQL "+error);
}
else
{
console.log("Connected with Database ");
}
});
app.set('port', process.env.PORT || 3000);
app.get('/',function(req,res){
res.send('hello index');
});
app.get('/load',function(req,res){
console.log("/load hit");
connection.query("SELECT * from user",function(err,rows){
if(err)
{
console.log("Problem with MySQL"+err);
}
else
{
res.end(JSON.stringify(rows));
}
});
});
/*start the server */
app.listen(3000,function(){
console.log("its started on PORT %s", app.settings.port);
});
this should take all the data in the user table and put it to JSON when I use /load. But I cant get Postman to display the data. This is the address I have been using
http://130.211.90.249:3000/load
The address is from Google cloud the port is the one I set in the server.js file and /load should use the function I have written above.
Why am I not seeing a result with this input? I am running the server with 'node server.js' on my VM instance and it says I have successfully connected.
Any help is really appreciated.
Edit 1
This is what my VM looks like when I run the server.js
my_user_name#nodejs-2:~$ node server.js
its started on PORT 3000
Connected with Database
No error but in Postman I get "Could not get any response" when I put in the address given above.
Edit 2
Do I need to create a http server in the server.js file that I run so that the JSON object can be reached by the request in Postman?
Edit 3
If I follow the ip address of my google cloud VM it takes me to a default page for Bitnami but tells me that node js is running in the cloud. Do I need to remove this default page or is it fine to just leave whilst the server runs?
Here is a link http://130.211.90.249/
Since the app is listening on port 3000 in your code, you need to create a firewall rule to make that port available from the outside.
From the developer console for that project, go to Networks and view the details for the default network. Create a rule to allow traffic on port 3000.

"Object is not a function" when passing a Node.js HTTP server object to Socket.IO

This was working a few months ago when I was creating an HTTPS server, but I switched to http (not sure this switch is directly related, just mentioning it in case) today when revisiting this application, where I create a server and pass it to socket.io:
init.js
var server = require(dirPath + "/custom_modules/server").serve(80);
var socket = require(dirPath + "/custom_modules/socket").socket(server);
It is important that I pass the server to socket.io (I know there are alternate ways of initializing the socket) this way because that's how it has to be done in order to encrypt the websocket connection when I switch back to serving HTTPS later.
So my server module:
//serve files
module.exports.serve = function(port) {
//var server = https.createServer(options, function(req, res) { // SSL Disabled
var server = http.createServer(function(req, res) {
// Parse & process URL
var reqInfo = url.parse(req.url, true, true), path = reqInfo.pathname;
// Quickly handle preloaded requests
if (preloaded[path])
preloadReqHandler(req, res, preloaded[path], path);
// Handle general requests
else
generalReqHandler(req, res, reqInfo);
}).listen(port);
return server; //this should be returning an http server object for socket.io
};
and my socket module:
module.exports.socket = function(server) {
//create socket
var socket = require(dirPath + '/node_modules/socket.io')(server);
// ^ error
// .. snip ..
//handle client connection
socket.on("connection", function(client) {
// .. snip ..
});
};
and my error:
/home/ec2-user/Sales_Freak/server/custom_modules/socket.js:17
var socket = require(dirPath + '/node_modules/socket.io')(server);
^
TypeError: object is not a function
at Object.module.exports.socket (/home/ec2-user/Sales_Freak/server/custom_modules/socket.js:17:59)
at Object.<anonymous> (/home/ec2-user/Sales_Freak/server/init.js:16:59)
Assume all of the necessary Node.JS modules are required properly above. What silly mistake am I making today?
The exported module is not a function, refer to your previous statement:
var socket = require(dirPath + "/custom_modules/socket").socket(server);
And compare that to your current statement:
var socket = require(dirPath + '/node_modules/socket.io')(server);
I think you meant to do this instead.
var socket = require(dirPath + '/node_modules/socket.io').socket(server);
This might or might not be helpful to others, but my problem was that I changed the directory of my Node.js server files and socket.io wasn't installed in the new location.
The module was there in node_modules but not installed. I'm actually not sure how installation works with npm modules, but the module existed and therefore didnt throw an error saying it didnt exist, but did not act like it was really there until I did npm install socket.io
If you get this error in this situation, you forgot install socket.io.

Categories