localhost:3000 JavaScript Problem in de app.get - javascript

I'm learning Js.
I have a problem in the code:
const express = require('express');
const app = express();
const PORT = 3000;
app.listen(PORT, function(){
console.log("The Express is running");
});
app.get('/', (req,res)=>{
res.send('Ok');
});
running node app.js i have the answer "Ok".But, running in the browser(localhost:3000) i get : "The connection was refused".
necessary info: I'm use a container docker, which I use the ubuntu. Can this cause a problem?

Related

Why is Express.js listening on two ports under WSL?

Express is set to listen on port 9999, when the message Listening on http://localhost:9999 appears in the terminal and I click on it, it opens a web browser to http://localhost:10000.
Both port 9999 and 10000 are responding to requests.
Code:
const express = require("express");
const app = express();
const port = 9999;
const host = "localhost";
app.get("/", (req, res) => {
res.send("Hello World");
});
const server = app.listen(port, host, () => {
const url = `http://${host}:${server.address().port}`;
console.log(`Listening on ${url}`);
});
terminal:
$ curl http://localhost:9999
Hello World
$ curl http://localhost:10000
Hello World
This seems to be specific to running it on Windows 10 WSL. Running this in a native Debian environment didn't produce the same result.
What is happening here? Is this a WSL thing?

Nuxt JS with WebSockets

I have a Nuxt App, with one service which needs to be delivered over WebSockets. The Nuxt App Server provides an api service using express.
I have an /api folder in which there are various *.js files, and these are routed to successfully. ie...
const express = require('express');
const app = express();
app.get('/whatever1',(req, res) => console.log('req.url',req.url))
works OK.
However the following, in the same file, will never be reached....
const express = require('express');
const app = express();
const expressWs = require('express-ws')(app);
app.ws('/whatever2',(ws,req) => {
console.log('req.url',req.url);
})
Where am I going wrong ?
You're attempting to connect the client to an endpoint on the server where no such endpoint exists. In your client's output, you're receiving an error of:
VM1295:1 WebSocket connection to 'ws://localhost:3000/api/whatever2' failed: Connection closed before receiving a handshake response
because you haven't defined a route of /api/whatever2. Your code above routes to:
ws://localhost:3000/whatever2
instead of ws://localhost:3000/api/whatever2
EDIT:
Here's test code that worked for me:
const express = require('express');
var app = express();
const expressWS = require('express-ws')(app);
expressWS.getWss().on('connection', function (ws) {
console.log('connection open');
});
app.ws('/whatever', (ws, res) => {
console.log('socket', ws);
});
app.listen(3000, () => console.log('listening on 3000...'));

How to export file and running app

I'm trying to create 2 seperate files in my app,
one for API request, and second one for socket.io
The starting file is app.js which look like this:
const express = require('express');
const app = express();
app.get('/test', (req, res) => {
res.send('test');
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
module.exports = app;
and the second file for socket.io looks like this:
const app = require('./app');
const http = require('http').Server(app);
const io = require('socket.io')(http);
...
http.listen(port, function(){
console.log('listening on *: ',port);
});
When I run the app with my IDE (VSCODE) everything works perfect,
but when I'm trying to run on the terminal the app doesn't start and the page isn't available on the starting port.
I think that the problem is about the export for the socketIO file in app.js,
Any help would be appreciated.

Sending Status Codes in NodeJS when serving static content

I am building a simple nodejs server to serve static content for a webpage. I want to send status codes back but when I try to create a function for the app.use() the content is not served.
var express = require('express')
var app = express();
app.listen(3000, function() {
console.log("We are now listening on Port:3000")
app.use(express.static('public'));
app.use('*', express.static('public/404.html'));
});
The content is served when I run this, but I cannot get the status codes as I need. Any help is appreciated.
I don't know exactly what you want. This is my suggest solution:
var express = require('express')
var app = express();
app.listen(3000, function() {
console.log("We are now listening on Port:3000")
app.use(express.static('public'));
app.use('*', function(req, res) {
// change your status code here
res.status(404).sendFile(__dirname + "/public/404.html");
});
});

"waiting for connections on port 27017" connecting to mongoose

I"m getting this message when I run mongod.
In the tutorial I'm doing, I think I should be getting something like "connection accepted from 127.0.0.16:6.."
I checked out this post already - mongod HostnameCanonicalizationWorker error on OS X
and I have my hosts file set up as such:
127.0.0.1 localhost
127.0.0.1 Bens-MacBook-Pro.local
255.255.255.255 broadcasthost
::1 localhost
These are my scripts for Node:
// Main starting point of the application
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const app = express();
const morgan = require('morgan');
const router = require('./router');
const mongoose = require('mongoose');
// DB Setup
mongoose.connect('mongodb://localhost:auth/auth');
// App Setup
app.use(morgan('combined'));
app.use(bodyParser.json({type: '*/*' }));
router(app);
// Server Setup
const port = process.env.PORT || 3090;
const server = http.createServer(app);
server.listen(port);
console.log('Server listening on:', port);
This is the log for mongod:
2016-11-20T16:33:13.095-0700 I CONTROL [initandlisten] MongoDB starting : pid=15054 port=27017 dbpath=/data/db 64-bit host=Bens-MacBook-Pro.local
......
2016-11-20T16:33:13.380-0700 I NETWORK [initandlisten] waiting for connections on port 27017
What is missing?
Thanks!
UPDATED
http://code.runnable.com/UWxv-JS8trEHAACH/connect-to-mongodb-using-mongoosejs-for-node-js
I added a listener to check for connection:
/*
* More details here http://mongoosejs.com/docs/index.html
*/
//require mongoose node module
var mongoose = require('mongoose');
//connect to local mongodb database
var db = mongoose.connect('mongodb://127.0.0.1:27017/test');
//attach lister to connected event
mongoose.connection.once('connected', function() {
console.log("Connected to database")
});
And it is logging "Connected to database" so it appears to be connected even thought the mongod window says it's not. Let me go through the rest of the tutorial and see if it's truly connected.
You are making some errors
mongoose.connect('mongodb://localhost:auth/auth'); is looking for a port :auth that does not exist
const server = http.createServer(app); you can simply do app.listen(port);
router(app); you can simply do require('yourRouteFile.js')(app);
You should get it going with the following server.js
// Main starting point of the application
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const app = express();
const morgan = require('morgan');
const mongoose = require('mongoose');
const port = process.env.PORT || 3090;
// DB Setup
mongoose.connect('mongodb://localhost/auth');
// App Setup
app.use(morgan('combined'));
app.use(bodyParser.json({type: '*/*' }));
//Routes
require('yourRouteFile.js')(app);
// Server Setup
app.listen(port);
console.log('Server listening on:', port);
Ok. So i followed the rest of the node + mongoose tutorial and using postman, I was able to save stuff to the db, verified by Robomongo. But my log with mongod still says "waiting for connections on port 27017". So I am not sure why.....But things work.

Categories