On my debian server, I installed node and then started node server on port 3000. The server is running, but it isn't visible from the browser
Now when I try to get it running via my domain or via my ip(for example xx.xxx.xx.xx:3000) or my domain (my-domain.com:3000) in both cases it doesn't work. I think I don't quite get the concept and I tried to search for a billion different things, but I can't find the solution to my problem. Could someone tell me, if I need to setup something else, too?
My server js code is
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
server.listen(3000, () => {
console.log('listening on *:3000');
});
io.on('connection', function (socket) {
socket.on( 'new_message', function( data ) {
io.sockets.emit( 'new_message', {
message: data.message,
date: data.date,
msgcount: data.msgcount
});
});
});
Error i got
You need to listen for GET requests in order to respond to them.
Try adding something like:
app.get('/', function (req, res) {
res.send('GET request test.')
})
In your case make sure you add the route before passing the app to the http.createServer() method, or otherwise just use something like app.listen(3000).
More info in the docs: https://expressjs.com/en/guide/routing.html
why are you using express and http both packages.
you can run server by either of them.
and then add a get route for it.
import { createServer } from "http";
import { Server } from "socket.io";
const httpServer = createServer();
const io = new Server(httpServer, {
// ...
});
io.on("connection", (socket) => {
// ...
});
httpServer.listen(3000);
I hope this will work!
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);
});
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.
I am currently trying to use socket.io and a node.js server to communicate with a Unity script. I have everything hooked up and working with localhost, but for some reason when I port it to my Heroku server it can't connect. I'm assuming it might have something to do with the URL's? I'm new to socket.io so any help would be appreciated.
My node.js server:
var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);
var path = require('path');
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(socket) {
socket.on('beep', function(){
socket.emit("speed", {data: 5});
console.log('beep recieved');
});
socket.on('change-speed', function(data) {
console.log('change speed recieved: ' + data);
socket.emit("speed", {newSpeed: data});
});
socket.on('ios-connection', function(data) {
console.log('ios connection with message: ' + data);
});
});
app.set('port', (process.env.PORT || 5000));
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
My connection URL:
ws://<heroku app name>.herokuapp.com:5000/socket.io/?EIO=4&transport=websocket
The problem is almost certainly an incorrect port number.
In your application, you are checking for process.env.PORT and if it is not set, you are defaulting to 5000.
In your ws URL however, you seem to be always expecting your application to be listening on port 5000.
You can check the config settings of your application by running the following command in the root of your project:
heroku run printenv
This will print a list of config vars, including the current set PORT value, eg:
PORT=9352
You should use this port when constructing your ws URLs, eg:
ws://your-app.herokuapp.com:9352/socket.io/?EIO=4&transport=websocket
I found the way!!.
In Unity
if you run server in the localhost. the url should have " : port"
example (port = 5000)
ws://127.0.0.1:5000/socket.io/?EIO=4&transport=websocket
but if you have deployed to **heroku
the url must delete " : port"
ws://<heroku app name>.herokuapp.com/socket.io/?EIO=4&transport=websocket
It's work for me!
I have deployed your code with minor changes and its working fine on heroku please take a look into it.
Server side app.js
var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 5000));
var server = app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
var io = require('socket.io')(server);
app.use(express.static("./views"));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.get('/', function (req, res) {
var path = __dirname + '/views/index.html';
console.log(path);
res.sendFile(path);
});
io.on('connection', function(socket) {
socket.on('beep', function(){
socket.emit("beep", {data: 5});
console.log('beep recieved');
});
socket.on('change-speed', function(data) {
console.log('change speed recieved: ' + data);
socket.emit("speed", {newSpeed: data});
});
socket.on('ios-connection', function(data) {
console.log('ios connection with message: ' + data);
});
});
package.json
{
"name": "socketio",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start" : "node app.js"
},
"author": "inampaki",
"license": "ISC",
"dependencies": {
"express": "^4.13.3",
"express-ws": "^0.2.6",
"socket.io": "^1.3.7"
}
}
index.html
<script src="/socket.io.js"></script>
<script>
var socket = io.connect('/');
socket.on('speed', function (data) {
console.log('speed Message Received!');
console.log(data);
});
socket.on('beep', function (data) {
console.log('beep Message Received!');
console.log(data);
});
socket.emit("beep", {beep : true});
socket.emit("change-speed", {"change-speed" : true});
socket.emit("ios-connection", {"ios-connection" : true});
</script>
note that save index.html and socket.io.js in views folder. URL on which I have deployed it is socketip
Ok, for some reason I tried everything on this question thread, and it worked. However not a single answer worked, but a combination of every one.
First, I removed the :PORT part in the URL, sort of like Chinnawat Sirima says. It is now...
ws://.herokuapp.com/socket.io/?EIO=4&transport=websocket
Then, for some reason initiating the server with this code from dangalg's answer/teyou's repo did work (I also noticed teyou's url doesn't have the port either).
var express = require('express');
var app = express();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var PORT = process.env.PORT || 3000;
(more code here)
http.listen(PORT,function(){
console.log("Listening to port " + PORT);
});
Why do I say "for some reason"? Because I still don't know what I did lol. My guess is that I was setting the server in a way Heroku didn't like, but everyday localhost does. Because localhost doesn't care.
I'm just recompiling this because I've been in frustration with this problem for the last 8 hours, more or less. So I hope this helps someone else, to not lose valuable time and sleep.
(btw, I don't have a PORT variable in my Heroku, I have some other name, I guess that's another useless line but I'm not touching this anymore in case I break it again :D).
If you have deployed your application to Heroku, remove the port number from the URL of the server as given and it should work fine.
ws://<heroku app name>.herokuapp.com/socket.io/?EIO=4&transport=websocket When you test the app locally, you can access the socket via http://localhost:YOUR_PORT_NUMBER wheres, after deployment, you don't need to specify the port.
Had a bit of a nightmare with this. Ended up reading through the docs.
Server: https://www.npmjs.com/package/socket.io
Client: https://socket.io/docs/v4/client-initialization
It seems my structure was wrong see the docs.
In conjunction with Express
const app = require('express')();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.on('connection', () => { /* … */ });
server.listen(3000);
My full code.
const express = require('express')
const path = require('path');
const http = require('http')
const PORT = process.env.PORT || 5000
const app = express()
const server = http.createServer(app)
const cors = require("cors");
app.use(cors());
// Serve static files from the React app
app.use(express.static(path.join(__dirname, 'client/build')));
const io = require('socket.io')(server);
io.on("connection", (socket) => {
});
server.listen(PORT, () => console.log(`Server is running on port ${PORT}`));
And in my react code I am simply using.
const socket = io();
Hope this helps someone else
I'm trying to create an http server. The server is created correctly but does NOT show the html content. It works when I do it without listeners. What am I failing then?
app.js
var server = require("./server.js");
server.server3((req, res, html) => {
res.writeHead(200, {"Content-Type": "text/html"});
html.pipe(res);
res.end();
}, 3000, "./index.html");
server.js
function Server3(applyFunction, port, path) {
var fs = require("fs"),
html = fs.createReadStream(path.toString().trim()), // Create stream from path
http = require("http");
html.on("data", _ => {})
.on("end", () => { // create server when all data is ready
http.createServer(function(req, res){ // createServer method
applyFunction(req, res, html); // execute the function
}).listen(+port); // add the port
});
}
module.exports.server3 = Server3;
If you're just trying to create an HTTP server on node.js, using the express framework (npm install express --save) would simplify your life a great deal. If you place the index.html file in the same directory as app.js, you can create the server with the following 5 lines of code:
// Setup Express
const express = require("express");
const app = express();
// Use main directory to find HTML file
app.use(express.static(__dirname));
// Render index.html
app.get("/", (req, res) => res.render("index"));
// Start Server on port 3000
app.listen(3000, () => console.log('Server started on port 3000'));