I've checked out How to setup KoaJS in Openshift and it's still not working.
Here is a part of my package.json file:
"engines": {
"node": ">= 0.12.0",
"npm": ">= 1.0.0"
},
"dependencies": {
"co-busboy": "^1.3.0",
"forever": "^0.14.1",
"fs": "0.0.2",
"koa": "^0.18.1",
"koa-logger": "^1.2.2",
"koa-router": "^4.2.0",
"koa-static": "^1.4.9",
"path": "^0.11.14"
},
"devDependencies": {},
"bundleDependencies": [],
"private": true,
"main": "--harmony app.js"
And then to my app.js file.
This code works:
var http = require('http');
//var koa = require('koa');
//var app = koa();
var ip = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1',
port = process.env.OPENSHIFT_NODEJS_PORT || '8080';
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(port, ip);
console.log('Server running at http://'+ip+':'+port+'/');
This does not work:
var http = require('http');
var koa = require('koa');
var app = koa();
var ip = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1',
port = process.env.OPENSHIFT_NODEJS_PORT || '8080';
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(port, ip);
console.log('Server running at http://'+ip+':'+port+'/');
As you can see the only difference is that I have uncommented two lines.
Error:
Service Temporarily Unavailable
The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later.
Apache/2.2.15 (Red Hat) Server at fela-basickarl.rhcloud.com Port 80
Error logs on OpenShift state this:
...
.../app-root/runtime/repo/node_modules/koa/lib/application.js:179
function *respond(next) {
^
SyntaxError: Unexpected token *
...
A big duh.
console.log(process.versions); reveals that I am using node 0.10.25, even though I stated in package.json that I wish to use >= 0.12.0:
{ http_parser: '2.0',
node: '0.10.25',
v8: '3.14.5.10',
ares: '1.9.1',
uv: '0.10.23',
zlib: '1.2.3',
modules: '11',
openssl: '1.0.0-fips' }
What is causing OpenShift to not use 0.12.2?
Quick deploy 0.12
https://hub.openshift.com/quickstarts/128-node-js-0-12
For people that whishes to deplot nodejs 0.12 use the link above, there's a button Deploy.
0.12.2
To deploy the specific version 0.12.2 copy the directory .openshift from https://github.com/ryanj/nodejs-custom-version-openshift and overwrite your current projects .openshift directory (I am presuming you are using OpenShifts git that was created when the app was created).
Navigate your way to your-project/.openshift/markers/ and open the file NODEJS_VERSION and add 0.12.2 at the bottom. My file looks as so:
# Uncomment one of the version lines to select the node version to use.
# The last "non-blank" version line is the one picked up by the code in
# .openshift/lib/utils
# Default: 0.10.25
#
# 0.8.24
# 0.9.1
# 0.10.25
# 0.11.11
# 0.10.25
0.12.2
Then upload your project via git to OpenShift (be in your project root directory).
git add -A .
git commit -a -m "replaced .openshift directory"
git push
--harmony flag?
as stated in ECMAScript 6 features available in Node.js 0.12 --harmony flag is still needed for certain functions.
This means adding it too your package.json file, look at my question to see an example.
Related
I am working on a project with Node.js, React.js and MongoDB.
When I send request to server, I get the following error:
Error occurred while trying to proxy request /api/auth/login from localhost:3000 to http://localhost:6000 (ECONNRESET).
I have my client running at port 3000, server at port 6000 locally. Here is the client side proxy middleware setup code:
const proxy = require("http-proxy-middleware");
module.exports = function(app) {
app.use(proxy("/api/", { target: "http://localhost:6000", "secure": "false" }));
};
I have tried using 127.0.0.1 inplace of localhost, but didn't work.
The project works fine in Windows laptop. But, it is having problem with M1 Mac.
Any guidance would be of great help to me.
I got the same error using M1.
This code started working correctly for me.
http://localhost:3000/ -> http://127.0.0.1:3000/
server.js
"use strict";
const express = require("express");
const { createProxyMiddleware } = require("http-proxy-middleware");
const PORT = 9090;
const HOST = "0.0.0.0";
const app = express();
app.use(
createProxyMiddleware("/", {
target: "http://127.0.0.1:3000/",
})
);
app.listen(PORT, HOST);
packege.json
{
"name": "web",
"version": "1.0.8",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "^4.18.2",
"http-proxy-middleware": "^2.0.6"
}
}
node v18.11.0
npm 8.19.2
Server at "http://127.0.0.1:3000/" - default configuration for create-react-app ("react-scripts": "^5.0.1")
I changed the version of Node.js to 14.9.0 and it worked.
These are the solutions found in the internet that didn't work for me:
Changing node.js version to other stable version 16 or 18
specifying an IPv4 address like this on server (because I can see my server was running on IPv6): server.listen(13882, "0.0.0.0", function() { });
Removing proxy entry from the Package.json file
Updating to {target: "http://localhost:6000/"} OR {target: "https://localhost:6000/"} OR {target: "http://127.0.0.1:6000"} OR
{'http://[::1]:6000'} OR {app.use(proxy("/api/", {target:"http://localhost:6000",secure: false,changeOrigin: true}));}
I have this entry in package.json file "proxy": "http://localhost:6000"
This is my setupProxy.js file
const proxy = require("http-proxy-middleware");
module.exports = function(app) {
app.use(proxy("/api/", { target: "http://localhost:6000" }));
};
I created a node app in openshift, I connected through SSH, and I was able to push my code and I could change the server.js code for a simple hello world.
Server.js
#!/bin/env node
var http = require('http');
var serverIp = process.env.OPENSHIFT_NODEJS_IP;
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
//creating server
var server = http.createServer(function(req, res) {
res.writeHead('Content-Type', 'text/plain');
res.end('Simple example!!');
});
//listening
server.listen(port, serverIp, function() {
console.log('Server started on port ' + port + ' IP: ' + serverIp);
});
When push this new code, I'm not getting any errors.
And this is the package.json file
{ "name": "Hello_world",
"version": "1.0.0",
"description": "Hello world",
"engines": {
"node": ">= 0.6.0",
"npm": ">= 1.0.0"
},
"devDependencies": {},
"bundleDependencies": [],
"private": true,
"scripts": {
"start" : "node server.js"
},
"main": "server.js"
}
When I do this, the application gets very very slow (like 2/3 minutes of waiting), here's the link.
[http://avalecia-minisis.rhcloud.com/]enter code here1
But when I change the code for the original, everything's fine... :/
I don't see where the issue could be.
When deploying to OpenShift, your application's build process can be optimized (or tuned) in a variety of ways.
If you'd like to minimize downtime between deploys, you can try enabling the hot_deploy feature:
mkdir .openshift ; mkdir .openshift/markers ; touch .openshift/markers/hot_deploy
git add .openshift/markers/hot_deploy
git commit -m "enabling the hot_deploy marker to minimize downtime on OpenShift"
git push
Checking in your node_modules folder can also have a major impact on build time.
Turning on NPM_CONFIG_PRODUCTION is another approach that may help (see : Run npm install --production on OpenShift)
I used the express generator to create a simple express app, which when started on dev works fine on localhost:3000.
When I push this to elastic beanstalk using the eb command-- git aws.push, however, I get a 502 error on the production server.
Looking into the logs, the error I get is:
2014/04/01 19:29:40 [error] 24204#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.2.178, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8081/", host: "macenvexp-env-hqv9ucmzev.elasticbeanstalk.com"
2014/04/01 19:29:40 [error] 24204#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.2.178, server: , request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:8081/favicon.ico", host: "macenvexp-env-hqv9ucmzev.elasticbeanstalk.com"
I'm using the default nginx configuration. When I run a node.js sample app without Express, it works fine. Here's the express code in app.js:
var express = require('express');
var http = require('http');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes');
var users = require('./routes/user');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
app.get('/', routes.index);
app.get('/users', users.list);
/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
And here's the package.json file:
{
"name": "macEnvExp",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "DEBUG=macEnvExp node bin/www"
},
"dependencies": {
"express": "~3.4.8",
"static-favicon": "~1.0.0",
"morgan": "~1.0.0",
"cookie-parser": "~1.0.1",
"body-parser": "~1.0.0",
"debug": "~0.7.4",
"jade": "~1.3.0"
}
}
And here is bin/www:
#!/usr/bin/env node
var debug = require('debug')('my-application');
var app = require('../app');
app.configure(function(){
app.set('port', process.env.PORT || 3000);
});
console.log(app.get('port'));
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
For clarity, I'll state the answer from the comments.
AWS ELB runs node app.js BEFORE npm start. node app.js doesn't give an error, but it doesn't open any ports.
The solution is to simply rename app.js to anything else except server.js (ie main.js) and reference that in bin/www by pointing to it in the /bin/www file: var app = require('../app'); to var app = require('../main');
Then it should be working correctly!
For clarity, here is what my directory looks like:
The package.json file will get called by ELB when it launches the application server. Here it has the instruction to run the start script node bin/www
This is the bin/www file that gets run. We see the require to ../main and the app.set('port'...)
Then the main.js file that runs the routing and all:
When I created the project, the main.js file was named app.js. The problem this caused was based on the priority ELB start sequences. ELB will launch the application and check first to see if app.js exists -- if it does exist, it runs node app.js, otherwise it will check if package.json exists and try to run npm start.
When the main.js had the name app.js ELB tried to start the whole application by running it. However this file doesn't open any ports.
An alternative to renaming app.js is to create an elastic beanstalk configuration file. Add a .config file into the .ebextensions folder, for example, .ebextensions/34.config. Change the NodeCommand setting in the namespace aws:elasticbeanstalk:container:nodejs to whatever command you want to run to start the server. For example, this is a minimal .config file to run npm start instead of app.js:
option_settings:
- namespace: aws:elasticbeanstalk:container:nodejs
option_name: NodeCommand
value: "npm start"
See http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_nodejs_custom_container.html and http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options.html#command-options-nodejs for more information.
Edit:
An even easier way - using the AWS console, Configuration/Software has the "Node command" option - just set that to npm start.
Set running port to 8081
app.set('port', 8081);
Actually, there is another option.
At the Elastic Beanstalk console, inside your app-environment section, there is a Configuration menu item on your left side (right bellow Dashboard menu option). If you click there, you will find many configuration options. Click at Software Configuration and then define which is your node command. There explain the order of commands it tries indeed: "Command to start the Node.js application. If an empty string is specified, app.js is used, then server.js, then "npm start" in that order"
My mistake was at my start command script. It was starting nodemon:
"scripts": {
"start": "NODE_ENV=production && nodemon ./bin/www"
Then I changed to node and it worked:
"scripts": {
"start": "NODE_ENV=production && node ./bin/www"
Hope I helped someone.
If you use port 8081 for running your express app and use sudo for running node server, Your application will be accessed directly from elasticbean url without port numbers, otherwise it will display a 502 Gateway error from nginx.
Nginx proxying 8081 port by default for node app on elastibeanstalk.
Create file: .ebextensions/nodecommand.config and put the option settings below:
option_settings:
aws:elasticbeanstalk:container:nodejs:
NodeCommand: sudo pm2 start server.js (server command with sudo ie. sudo node /bin/www)
You can create another file for container commands: .ebextensions/01_init.config and put the desired commands which will be run before deployment. For example:
container_commands:
01_node_v6_install:
command: sudo curl --silent --location https://rpm.nodesource.com/setup_6.x | bash -
02_install_node:
command: sudo yum -y install nodejs
03_npm_install_gulp_webpack:
command: sudo npm install -g gulp webpack pm2
04_npm_install:
command: sudo npm install
05_webpack_run:
command: sudo webpack
In case anyone did the silly thing I did, make sure your bin folder is committed if you are using express. I had mine in my .gitignore file and this is why I was getting a 502 error.
Just remove /bin from .gitignore, commit, and the deploy changes to EB.
new to AWS and been a while since i webdeved, but was stuck tonight on same issue, and thanks to everyone in the thread, i am very happy to say that basic socket.io tutorial works now like a charm, i was just forgetting one line in package.json :
"scripts":
{
"start": "node app.js"
}
oh, and port !
the only thing i kept from elasticbean sample node.js app is this value instead of pure 3000 value :
var port = process.env.PORT || 3000;
Note: I ran into this issue and none of the solutions were working for me.
My solution was to make sure the devDependencies in package.json were actually in dependencies.
For example:
{
"name": "whaler-test",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www",
"create-db": "cd dynamodb && node createDonorsTable.js && cd ..",
"delete-db": "cd dynamodb && node deleteDonorsTable.js && cd ..",
"load-data": "cd dynamodb && node loadDonorsData.js && cd ..",
"read-data": "cd dynamodb && node readDataTest.js && cd .."
},
"dependencies": {
"cookie-parser": "~1.4.3",
"debug": "~2.6.9",
"express": "~4.16.0",
"http-errors": "~1.6.2",
"jade": "~1.11.0",
"morgan": "~1.9.0",
"nodemon": "1.17.5",
"cors": "2.8.4",
"aws-sdk": "^2.270.1"
}
}
Not:
{
"name": "whaler-test",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www",
"create-db": "cd dynamodb && node createDonorsTable.js && cd ..",
"delete-db": "cd dynamodb && node deleteDonorsTable.js && cd ..",
"load-data": "cd dynamodb && node loadDonorsData.js && cd ..",
"read-data": "cd dynamodb && node readDataTest.js && cd .."
},
"dependencies": {
"cookie-parser": "~1.4.3",
"debug": "~2.6.9",
"express": "~4.16.0",
"http-errors": "~1.6.2",
"jade": "~1.11.0",
"morgan": "~1.9.0",
"nodemon": "1.17.5"
},
devDependencies {
"cors": "2.8.4",
"aws-sdk": "^2.270.1"
}
}
We'd like to surf the internet through a node.js proxy on appfog.
We tried this code:
proxy2a.js:
var http = require('http');
var port = process.env.VCAP_APP_PORT || 8080;
console.log ('the portnumber is: '+ port) ;
http.createServer(function(request, response) {
var proxy = http.createClient(80, "checkip.dyndns.org");
var proxy_request = proxy.request(request.method, request.url, request.headers);
proxy_request.on('response', function (proxy_response) {
proxy_response.pipe(response);
response.writeHead(proxy_response.statusCode, proxy_response.headers);
console.log(proxy_response.statusCode) ;
});
request.pipe(proxy_request);
}).listen(port);
package.json:
{
"name": "proxy2a",
"author": "parker",
"version": "0.0.0-14",
"dependencies": {
},
"devDependencies": {},
"optionalDependencies": {},
"engines": {
"node": "0.6.x",
"iisnode": "*"
},
"scripts": {
"start": "node proxy2a.js"
}
}
We have the code from this question. (Actually we need the server only to access one website, so it is fine that this server only serves one.)
This code works great when we run the server on our local machine.(Use node version 0.6.x.)
But when we deploy to appfog, there is no reaction. (We get the ip by pinging the deploy url with another console.) Do you know how to get such a proxy server to work on appfog or any other node.js host?
Your code works exactly as-is for me. I copied your two files as-is, and ran the following commands--
af login
// enter my creds
af update testproxy
Then went to http://testproxy.aws.af.cm/ and it works. Are you sure you uploading your app correctly, are using the correct domain name, and that your app is started?
(VCAP_APP_PORT is set to 80, so your app will be running on port 80 due to this line: var port = process.env.VCAP_APP_PORT || 8080;)
Whenever I try to use require("socket.io"); on heroku it fails with the message "Cannot find module socket.io".
I think it’s an issue with my setup, because the same is running fine in my local node.js server.
What do I have to change?
Heroku on cedar does not support websockets
Anyway you can use socket.io with
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10);
https://devcenter.heroku.com/articles/using-socket-io-with-node-js-on-heroku
You have to change your PaaS provider. Heroku doesn't support websockets. Where as nodejitsu is known for support websockets.
Also, you might have forgot adding socket.io in package.json dependency lists.
package.json modified as
"dependencies": {
"async": "0.1.18",
"ejs": "0.4.3",
"express": "2.4.6",
"faceplate": "0.0.4",
"socket.io": "latest" },
And the serverside code is:
var port=process.env.PORT || 3000;
var http=require('http');
var app=http.createServer(function(req,res){
res.write("server listening to port:"+port);
res.end();
}).listen(port);
socket=require("socket.io");
io=socket.listen(app);
io.configure(function () {
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10);
});
io.sockets.on("connection",function(socket){
console.log("new connection");
socket.on("eventA",function(data){
io.sockets.emit("eventB",data);
});
});
Working like a charm!!!
You need to change the transport option on socket.IO to xhr-polling with a (10) second duration, according to this project wiki page.
websocket transport is working on Heroku in beta state. you can enable it with heroku labs:enable websockets -a YOUR_APP_NAME
These are solutions to socket.io related problems
I hope i will work
Ports in your (index.js or server.js) & (index.html and your client.js) port must be different. (refer below code)
=============your index.js file ======================
(port here is 8000)
const express = require("express")
var app = express();
const http = require('http')
var server = http.createServer(app);
const port = process.env.PORT || 8000
server.listen(port,()=>
{
console.log("Listening at port => "+port)
});
var io = require('socket.io')(server, {
cors: {
origin: '*',
}
});
const cors = require("cors")
app.use(cors())
=============your client.js file ======================
port here is 8080
const socket = io.connect('https://localhost:8080/')
=============your index.html file ======================
port here is 8080
<script defer src="https://localhost:8080/socket.io/socket.io.js">
</script>
Remember your "server.js or index.js" port should be different from "client.js" port (Rememeber this is important)
(index.html and your client.js) port must be same
You should always use 'http' while working with socket.io (refer above code)
U may not included cors as it allows u to have more resourses , without cors heroku prevent some dependencies to not install in heroku (refer above code)
Try replacing "io" to "io.connect"
const socket = io.connect('https://localhost:8080/')
Must write tag at the end in the HTML
U may forget to add this code which is must in "socket.io"
It is required in your html file
delete "node_modules" and "package-lock.json"
and write "npm i" in cmd
This should be in package.json 's scripts
"start":"node index.js",
I am not talking about nodemon , use simple node over here
May be version is creating a problem , u can avoid it by copying all "devDependencies" to "dependencies" in "package.json" and put "*" in version like this
"dependencies": {
"cors": "*",
"express": "*",
"nodemon": "*",
"socket.io": "*"
},
"devDependencies": {}