Can't get Hello World with Node.js in Cloud9 - node.js

I can't figure out how to get my server to respond with Hello World.
I don't even know what IP address is. Is the ip listed on the tab of my terminal it?
I just created an EC2 environment with the default Node.js template.
Do I need to setup more things beforehand?
https://i.stack.imgur.com/4m85x.png

Try the solution bellow and let me know if you need any explanation:
const http = require("http");
const port = 3000; // make sure the port number is not used
const requestHandler = (req, res) => {
req.on('Error occurerd', (err) => {
console.error(err);
res.end();
});
res.end("Hello from AWS Cloud9!");
}
const server = http.createServer(requestHandler);
server.listen(port, () => {
console.log(`Server is listening on port ${port}!`);
// Run your script then copy past this url in your browser 127.0.0.1:3000
});

Related

I am building container with node. but I can't connect app in container [duplicate]

This question already has answers here:
Containerized Node server inaccessible with server.listen(port, '127.0.0.1')
(2 answers)
Closed 8 months ago.
I am building container with node.
I have two type of codes. I think two codes very simple and similar. and package.json and Dockerfile is same. just different code.
but I can connect app in container. but the other one can't connect app in container.
This code is working well in container.
const express = require('express')
const PORT = 3000;
const app = express();
app.get('/',(req,res)=>{
res.send('Hello World');
});
app.listen(PORT);
console.log('Running');
but This code is not working What wrong with this? this is node official sample 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('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
please tell me what problem is.
Thank you in advance
The sample code works when run on the host machine, but not when run in a container.
The issue is that the sample code binds to the 127.0.0.1 IP address. That means that it'll only accept connections from localhost.
In a container, localhost is the container itself. So when you try to connect from the docker host, it looks like the connection comes from another machine and the connection is rejected.
To fix it, you need to make it accept connections from outside the container. You can do that by changing the hostname variable to 0.0.0.0 like this
const http = require('http');
const hostname = '0.0.0.0';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
You can also leave out the hostname variable on the server.listen call as you've done in the first program. The default value is 0.0.0.0, so leaving it out also works.

how to connect via WebSocket running on Ubuntu server

Im have hetzner server on which im trying to run WebSocket. Unfortunately I got stack so here is my code from test.js)
const https = require('https');
const fs = require('fs');
const ws = require('ws');
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem'),
};
let server = http.createServer(options, (req, res) => {
console.log(req);
res.writeHead(200);
res.end();
});
server.addListener('upgrade', (req, res, head) => console.log('UPGRADE:', req.url));
server.on('error', (err) => console.error(err));
server.listen(8080, () => console.log('started on 8080'));
const wss = new ws.Server({ server, path: '/echo' });
wss.on('connection', (ws) => {
console.log('client connected');
ws.send('Hello');
ws.on('message', (data) => ws.send('Receive: ' + data));
});
wss.on('error', (e) => console.log(e));
* I got this code from some sources
After running the server I got message in console started on 8080. Nothing else... I tried to test it but I always got errors with no code. It looks like service where I tested it cannot find WebSocket. It is possible that problem actually in connecting to the serer.
Im not shure which path string should I use. I have hostname ubuntu-s**** and server IP 49.****. I did lots of attempts with 'wss://ubuntu-s***:8080/echo' and 'wss://49.***:8080/echo' but none of them gave any result
I still have no messages in console that cliend tried to connect :( Moreover I tried to run it on the local server (of course I removed SSL sertificates connecthion and changed server protocol to HTTP) and it works perfectly!!!
Thanks a lot for urs replies
UPD: message I got when trying to connect ws WebSocket connection to 'ws://49.***:8080/echo' failed:
First double check if the IP address is correct then change protocol to HTTP because you are using it on top of HTTP:
http://49.***:8080/echo

Create a nodejs app in oracle cloud ubuntu instance

I just create my oracle cloud ubuntu instance and I want to run a hello world Nodejs application and make it accessible to the internet.
But the problem is when I try to access it from my browser (http://public-ip-address:3000) doesn't work works.
I followed this instruction " https://gist.github.com/bradtraversy/cd90d1ed3c462fe3bddd11bf8953a896 "
but it doesn't work too
this is my app.js
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('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});

Node.js + React: How to POST

Follow on from this question: Axios can GET but not POST to the same URL
I've been trying to figure this out for too long now.
I want to POST from my React app to a .JSON file. Can anyone tell me what I'm doing wrong?
My AJAX POST function using axios always returns a 404. I'm listening for it on the node server but app.post never fires.
Thanks.
POST request from my React app:
postJson = (postJsonData) => {
axios.post('./postJson/', {
postJsonData
})
.then(function (response) {
console.log("success!");
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
app.js (node server):
/*========== Default Setup for node server copied from node website ==========*/
const http = require('http');
const hostname = '127.0.0.1';
const port = 3001;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
/*========== Listen for POST (Trying to get the data from my REACT app
- will then assign it to "obj" below) ==========*/
var express = require("express");
var myParser = require("body-parser");
var app = express();
app.post("./postJson/", function(request, response) {
console.log("MURRRR");
console.log(request.body); //This prints the JSON document received (if it is a JSON document)
/*=== JSON Stuff ===*/
var jsonfile = require('jsonfile')
var file = './scene-setup.json'
var obj = {name: 'JP'}
jsonfile.writeFile(file, obj, function (err) {
console.error(err)
})
});
//Start the server and make it listen for connections on port 3000
app.listen(3000, function(){
console.log("server is listening to 3000");
});
Two things I noticed:
Your post endpoint doesn't need a leading "." I would make it just "/postJson"
Make sure you are posting to "http://localhost:3000/postJson"
Make sure you have the network tab open to see the actual URL you are requesting to.
Cheers
Turns out both react and my node server were running on localhost:3000 simultaneously which is apparently not okay.
Running my node server on localhost:3001 from a new command line window allowed me to do both at the same time.
Not sure how this would work when making a production build though.

Can't access nodejs server on aws

I have an AWS EC2 instance which I am using for my node js application. I cannot access any application page on the server.
I wrote this simple code solely for testing purposes but I cannot access even this from my browser.
var express = require('express');
var app = express();
app.listen(3000, ()=> {
console.log('listening');
});
app.get('/',(req,res)=> {
res.send('hi');
});
On navigating to http://:3000, I should be able to see "hi" written but the request times out.
Here are my security group configs :
Solved the problem with some help.
Since the port available to me was port 80, so I just forwarded the port 8080 to port 80 via. port forwarding and it worked out.
Sharing the link from where I found the solution:installing nodejs and forwarding port on aws
My code (shown below) is a bit different, but I was having the same problem with connecting from a remote browser:
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('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
What I had to do was replace const hostname with the complete AWS server IP: ec2-xx-xx-xx-xx.compute-1.amazonaws.com:3000/
Make sure you have port 3000 open in your security group, or this will not work.
I was then able to connect to the NodeJS server from my browser on my PC.
Hope this helps. The corrected code is shown below (replace the x's with your actual IP address. You can get this on your EC2 dashboard.
const http = require('http');
const hostname = 'http://ec2-xx-xxx-xxx-xx.compute-1.amazonaws.com/';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
I got the code for this NodeJS server from:
https://websiteforstudents.com/install-the-latest-node-js-and-nmp-packages-on-ubuntu-16-04-18-04-lts/

Resources