I've just started learning node.js but when I try to launch the hello world code by writing on the terminal node server.js, localhost:3000 gives me the following error:
This page isn’t working;
localhost didn’t send any data.
ERR_EMPTY_RESPONSE
I've been searching for 2h now and I've found nothing. I've checked the port 3000 in cmd with netstat -a -n -o and it says that the port is listening (so I guess it is working). So what is preventing me from accesing to that port.
Here it my JS files:
server.js:
const http = require('http');
const app = require('./app');
const port = process.env.PORT || 3000;
const server = http.createServer();
server.listen(port);
app.js:
const { request } = require('express');
const express = require('express');
const app = express();
app.use((req, res, next) => {
res.status(200).json({
message: 'It works'
});
})
module.exports = app;
Add the required app to the createServer call:
const server = http.createServer(app);
In this way the http server can route your http requests to it.
Could process.env.PORT be set somewhere, causing your app to be hosted on that port instead?
An easy way to check would be to console.log the PORT variable in your script, and see if it has any value.
If it does have a value, trying going to localhost:PORT
Related
I'm working on my first project using react and node and have been stuck on this problem for a while. I keep getting this error when trying to connect to my site using the ip address, but if I just do localhost:3000 it works perfectly. I want to be able to connect via the IP address so I can test it across devices. Here is the full error:
[HPM] Error occurred while trying to proxy request /socket.io/?EIO=3&transport=polling&t=N4EqtUl&sid=kz_I098ZM2h1Z6WZAAAI from 192.168.0.4:3000 to http://192.168.0.4:5000 (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors)
I checkout out this post and implemented setupProxy.js like the second answer suggested, but it still isn't working.
Here is my node server (index.js):
const express = require('express');
const app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
const path = require('path')
const port = process.env.PORT || 5000;
app.use(express.static(path.join(__dirname, 'client/build')));
io.on('connection', function(socket) {
console.log('a user connected');
});
// Anything that doesn't match the above, send back index.html
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/client/build/index.html'))
})
http.listen(port || 5000, function () {
console.log('listening on', port);
});
I am trying to build a full stack app using ReactJS for the frontend and ExpressJS for the backend. I use Axios to make calls from my frontend to my backend. When I make those calls, I get these errors:
My express index file:
const express = require('express')
const path = require('path')
var app = express()
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`)
})
app.use(express.static(path.join(__dirname, "public")))
My get call from React frontend:
componentDidMount() {
axios.get("http://localhost:5000/servers.json").then((res => {
this.setState({ servers: res.data })
}))
}
React server is running on port 3000 and Express server is running port 5000, so there shouldn't be a conflict there...
The reason you are getting the error http://localhost:3000 is not allowed by Access-Control-Allow-Origin is because of the same origin policy, a security feature that's restricting your react script from accessing/communicating your server since they are from different origins. Please note that for documents or scripts to be considered as having the same origin they need to have the same protocol (e.g http / https), hostname (e.g localhost / www.my-server.com) and port. In your case port the react script runs at port 3000 while the express script is running on port 5000, thus the error.
To solve this, you need to enable CORS - Cross Origin Resource Sharing on your server side code. First install the cors dependency using the command
npm install cors
Then update the code in your server to look as follows:
const express = require('express')
const path = require('path')
const cors = require('cors')
const app = express()
app.use(cors())
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`)
})
app.use(express.static(path.join(__dirname, "public")))
Hopefully this works for you.
This looks like a basic cors issue. Add this cors middleware to your express server. It's the state of the art solution to this problem.
const express = require('express')
const path = require('path')
var cors = require('cors')
var app = express()
app.use(cors())
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`)
})
app.use(express.static(path.join(__dirname, "public")))
If you are interested about cors in general, check out the wikipedia page.
I'm trying to get socket.io working on my heorku app, but I think I'm having some trouble defining the ports. On the backend I have my express app listening to the process.env port or 5000, and I have my socket.io port listening on 8000.
Node.js
const express = require("express");
const app = express();
const server = require('http').Server(app)
const io = require('socket.io')(server)
const socketPort = 8000;
io.listen(socketPort);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port} !`));
And on my front end I have my socket to route requests to localhost:8000
Reactjs
const socket = io('http://localhost:8000')
//Open connection to backend
socket.on('connect', ()=>{
console.log("Connected");
})
It works just fine when I run it locally, but I can't get it working on Heroku - GET http://localhost:8000/socket.io/?EIO=3&transport=polling&t=MszLUDm net::ERR_CONNECTION_REFUSED
Is there a specific way I need to set up these ports? As far as I know I can only set up one process.env port. Should I be subbing something into the "localhost:8000" on the front end?
Thanks!
On the client side I ended up just declaring the socket like this:
const socket = io();
Leaving out the localhost:5000 part altogether.
Basically my socket.io server is only working for.. one computer only, I suppose. It works if I use Chrome, Chrome incognito, Edge. I tried using the app with my phone, while on the same Wifi, and that's where I encountered problems. It looked like socket.io just wouldn't work then. I feel like it's only working for one client (maybe ip, port issues?)
I use socket.io in pair with React js, and oh boy it was pain in the arse to make them work both locally and on Heroku.
Here's my server file /src/server/index.js
const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const axios = require("axios");
const port = process.env.PORT || 4001; // Only this port works for some reason
const index = require("./routes/index");
const app = express();
const path = require('path');
const server = http.createServer(app);
const io = socketIo(server); // < Interesting!
io = socketIo.listen(app);
io.configure(function () {
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10); // Recommended from online guys
});
app.use(express.static(path.join(__dirname, '../../index')));
app.get('/', (req, res, next) =>
res.sendFile(index))
io.on("connection", socket => {
console.log("New client connected");
})
server.listen(port, () => console.log(`Listening on port ${port}`));
I use config file to dynamically change the server and I import it every time I need to connect to my socket via socket.io-client
let server = 'ws://XXXXXXXXXXXXX.herokuapp.com/socket.io/?EIO=4&transport=websocket';
const env = process.env.NODE_ENV;
if (env === 'development') {
server = 'http://127.0.0.1:4001';
}
module.exports = server;
What could be the problem? Why is only working on my root computer? Could be a dyno problem or something else?
I'm a complete beginner with both heroku and socket.io, so any information would be helpful.
**EDIT:
I am not sure, but I feel like a server running in my VS Code made it work in my heroku app. I have turned it off and the server just keeps sending net::ERR_CONNECTION_REFUSED error.
Solution:
Using mars/heroku-cra-node buildpack is a must. It seperates react-ui and server code. Port config: const port = process.env.PORT || 4001,
Client listens for: let server = window.location.hostname
Also good to have a seperate config file for clientside that has the following:
const env = process.env.NODE_ENV;
if (env === 'development') {
server = 'http://localhost:4001';
}
module.exports = server;
Then you won't have to change ports and servers in development (VSCode) or production (Heroku).
I have an https expressjs server with websockets (using the 'ws' package). As far as I understand sockets and ports, I should be able to add a route alongside the websocket connections. The main use-case is so that the server can be curled (none of the ws curl requests I've seen online worked.)
Unfortunately I only have 1 port to use for the server and websockets. How can I set this up so that app and server can both listen on the same port?
I've seen a few comments on SO that indicates that it can be done, but no code examples, or it's for very different packages.
I'm using the 'ws' package: https://www.npmjs.com/package/ws
const port = 8888;
const http = require('http');
const https = require('https');
const express = require('express');
const websocket = require('ws');
const app = express();
app.use( express.static('public') );
app.get('/curl', (req, res) => res.send('Hello World')).listen( port );
const httpsServer = https.createServer( credentials, app );
const wss = new websocket.Server({ server: httpsServer });
httpsServer.listen( port, function listening(){
console.log( 'listening on ' + port );
});
Currently I get the "EADDRINUSE" error since I'm using the same port for two 'servers'.
FOLLOW-UP
Express app doesn't need to also listen if another server is.
To curl https, you have to provide the cert details, or use the '-k' (insecure) method.
Your code shows you trying to start two servers on the same port.
This line creates a new http server and attempts to start it on port 8888:
app.get('/curl', (req, res) => res.send('Hello World')).listen( port );
These lines create a new https server and attempt to start it on port 8888 also.
const httpsServer = https.createServer( credentials, app );
httpsServer.listen( port, function listening(){
console.log( 'listening on ' + port );
});
You cannot do that. If you just want one https server that works for both your web requests and your webSocket (a common way to do things), then change your code to this:
const port = 8888;
const https = require('https');
const express = require('express');
const websocket = require('ws');
const app = express();
app.use( express.static('public') );
app.get('/curl', (req, res) => res.send('Hello World'));
const httpsServer = https.createServer( credentials, app );
const wss = new websocket.Server({ server: httpsServer });
httpsServer.listen( port, function listening(){
console.log( 'listening on ' + port );
});
which just removes the .listen(port) that operates on the app object because that will create an http server and start it on the 8888 port.