i'm trying to have a socket working on my sever
here is my app.js file
console.log('app.js says hi');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.use(express.static(__dirname + '/bower_components'));
app.get('/', function(req, res,next) {
res.sendFile(__dirname + '/index.html');
});
server.listen(4200);
and my index.html file
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<h1>Hello World!</h1>
<div id="future"></div>
<form id="form" id="chat_form">
<input id="chat_input" type="text">
<input type="submit" value="Send">
</form>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:4200');
socket.on('connect', function(data) {
socket.emit('join', 'Hello World from client');
});
</script>
</body>
</html>
and in the console log I get this error:
GET http://localhost:4200/socket.io/?EIO=3&transport=polling&t=LsOF2yq net::ERR_CONNECTION_REFUSED
i found it
replace this line
var socket = io.connect('http://localhost:4200');
with
var socket = io.connect('http://yourdomain.com:4200');
Related
Trying out Node.js for the first time. My POST route is failing with "Cannot POST /admin/add-product.html". GET request is being served fine from the same route. I have had a look around here. Several answers to similar issues but nothing is helping. Here is my code:
./index.js
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const adminRoutes = require('./src/routes/admin');
const shopRoutes = require('./src/routes/shop');
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/admin', adminRoutes);
app.use(shopRoutes);
app.listen(3000);`
./src/routes/admin.js
const path = require('path');
const express = require('express');
const router = express.Router();
// served on /admin/add-product GET route
router.get('/add-product', (req, res, next) => {
res.sendFile(path.join(__dirname, '../', 'views', 'add-product.html'));
});
// served on /admin/add-product POST route
router.post('/add-product', (req, res, next) => {
console.log(req.body);
res.redirect('/');
// res.send('<h1>product saved</h1>');
});
module.exports = router;
./src/views/add-product.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Add Product</title>
</head>
<body>
<header>
<nav>
<ul>
<li>Shop</li>
<li>Add Product</li>
</ul>
</nav>
</header>
<main>
<form action="/admin/add-product.html" method="POST">
<input type="text" name="title" /><button type="submit">
Add Product
</button>
</form>
</main>
</body>
</html>
Thank you!!!
The action in the form need to match the route declare in the NodeJS application, it should be :
<form action="/admin/add-product" method="POST">
Remove the .HTML from the action attribute of the form.
Here is my code:
index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.get('/js/client_world.js', function(req, res){
res.sendFile(__dirname + '/js/client_world.js');
});
io.on('connection', function(socket){
console.log("A user is connected");
socket.on('disconnect', function(){
console.log("User disconnected");
});
});
http.listen(3000, function(){
console.log("Listenng to port 3000")
});
index.html:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="/socket.io/socket.io.js"></script>
<script src="//threejs.org/build/three.min.js"></script>
<script src="/js/client_world.js"></script>
</head>
<body>
<div id="container"></div>
<script>
var socket = io();
socket.on('connect', function(){
loadWorld();
});
</script>
</body>
</html>
and a third file, client_world,js, where I want to read data from a database.
The first line
var {Pool,Client} = require('pg');
causes an error.
Is this way to access the DB wrong? Thanks in advance for a hint.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
<title>Node file uploads</title>
</head>
<body>
<div class="container">
<h1>File upload</h1>
<%= typeof msg!= 'undefined' ? msg: ''%>
<form action="/upload" method="POST" enctype="multipart/form-data">
<div class="file-field input-field">
<div class="btn grey">
<span>File</span>
<input name="myImage" type="file">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text">
</div>
</div>
<button type="submit" class="btn">Submit</button>
</form>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
</body>
</html>
NODEJS CODE
const express = require('express');
const multer = require('multer');
const ejs = require('ejs');
const path= require('path');
const bodyParser = require('body-parser');
const app = express();
// middle ware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//set storage engine
const storage = multer.diskStorage({
destination: './public/uploads/',
filename:(res,file,cb)=>{
cb(null,file.fieldname+'-'+Date.now()+path.extname(file.originalname));
}
});
// init app
const upload = multer({storage:storage}).single('myImage');
const port = 3000;
// ejs
app.set('view engine','ejs');
//public folder
app.use(express.static('./public'));
// routing
app.get('/', (req,res)=>{
res.render('index');
});
app.post('/upload',(req,res)=>{
upload(res,res,(err)=>{
if(err){
res.render('index',{msg:err});
res.send('error uploading');
}else{
// console.log(req.file);
res.send('test');
}
});
});
app.listen(port,()=>{
console.log('server is connected at '+ port);
});
Error
TypeError: Cannot read property 'transfer-encoding' of undefined
at hasbody (/var/www/html/nodeuploads/node_modules/type-is/index.js:93:21)
at typeofrequest (/var/www/html/nodeuploads/node_modules/type-is/index.js:127:8)
at multerMiddleware (/var/www/html/nodeuploads/node_modules/multer/lib/make-middleware.js:18:10)
at app.post (/var/www/html/nodeuploads/app.js:40:4)
at Layer.handle [as handle_request] (/var/www/html/nodeuploads/node_modules/express/lib/router/layer.js:95:5)
at next (/var/www/html/nodeuploads/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/var/www/html/nodeuploads/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/var/www/html/nodeuploads/node_modules/express/lib/router/layer.js:95:5)
at /var/www/html/nodeuploads/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/var/www/html/nodeuploads/node_modules/express/lib/router/index.js:335:12)
When i click submit button below message is displayed
transfer-encoding' of undefined
Please let me know if additional details are required for debugging this issue
Thanks
I have problem with socket connection between client-side and server-side .
I have this code on server-side :-
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket) {
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
and this code on client-side :-
<html>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.1/socket.io.js"></script>
<script>
var socket = io();
</script>
</body>
</html>
the code in server-side is working , but in client-side i have these errors :-
can anyone help me to fix problem ?
Thanks a lot :(
Its looks like you are opening file directly into browser. Actually you are not specify path for serving your html. so that socketio can POST and poll data there.
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
If you really need to open file directly into browser rather than serving via nodejs on same port you have to specify host and port in client-side socket.
rather than simply using io() which will look for local port you can use this
var socket = io("http://localhost:3000");
So here how it works for me
// server
const app = require('express')();
const http = require('http').createServer(app);
// ^^^^^^^^^^^^
const io = require('socket.io')(http);
// here you should serve your index.html file
// and the socket io will know which socket to track
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
// client/index.html
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<script src="/socket.io/socket.io.js"></script>
<script>
// here it automatically track localhost:3000
var socket = io();
</script>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>
Hope it will help you
Please can you help me out, for some reason I am not able to post and am getting a "cannot POST /api/create" and when inspecting the page a 404 error is shown.
Here is my index.js:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mainRouter = require('./mainRouter.js');
var todoRoutes = require('./todoRoutes.js');
//tell express to use bodyParser for JSON and URL encoded form bodies
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
//mouting our routers
app.use('/', mainRouter);
app.use('/todo',todoRoutes);
app.listen(3000);
console.log("Express server running on port 3000");
And the corresponding todoRoutes.js file is where I require the post method:
var express = require('express');
var todoRoutes = express.Router();
var todoList = []; //to do list array
todoRoutes.get('/', function(req, res) {
res.sendFile(__dirname + '/views/todo/index.html');
});
todoRoutes.get('/create', function(req, res) {
res.sendFile(__dirname + '/views/todo/create.html');
});
todoRoutes.get('/api/list', function(req, res) {
res.json(todoList); //respond with JSON
});
todoRoutes.get('/api/get/:id',function(req, res){
res.json(todoList[req.params.id]);
});
todoRoutes.post('/api/create', function(req, res){
console.log("Creating the following todo:", req.body.todo);
todoList.push(req.body.todo);
res.send({redirect: '/api/list'});
});
and here is the corresponding html file:
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Todo List: Create</title>
<meta charset="utf-8" />
</head>
<body>
<form action = "/api/create" method="post">
<div>
<label for="todo">Enter your new Todo:</label>
<input type="text" id="todo" name="todo">
</div>
<div class="button">
<button type="submit">Add</button>
</div>
</form>
</body>
</html>
If I put a console.log("") in the POST function of the todoRoutes.js file it will not be displayed, indicating that the function does not even get executed.
Any help will be very much appreciated.
You need to POST to /todo/api/create, based on your current route handling:
<form action = "/todo/api/create" method="post">