I'm struggling with socket.io, express, and node.js.
I send data from an Arduino to my cmd. This is done with the serialport libary. But now I want this data displayed on my web browser. I'm using the express library for this. I have index.js here is the connection with the arduino and browser. And an index.html
This code do I have:
code from index.js (node.js server):
var express = require('express'),
app = express(),
server = require('http').Server(app),
io = require('socket.io')(server),
port = 8888;
//Server start
server.listen(port, () => console.log('on port' + port))
//user server
app.use(express.static(__dirname + '/public'));
io.on('connection', onConnection);
var connectedSocket = null;
function onConnection(socket){
connectedSocket = socket;
}
//Arduino to CMD
const SerialPort = require('serialport');
const Readline = SerialPort.parsers.Readline;
const usbport = new SerialPort('COM4');
const parser = usbport.pipe(new Readline());
parser.on('data', console.log);
The data what is recieved from the serialport (Arduino), had to be displayed in the index.html (webbrowser). I tried already something but it doesn't work. It has to be printed in the <p></p> in the html code.
The index.html code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<div id="text">
<p></p>
</div>
<script>
var text = document.getElementById('text');
var socket = io.connect('http://localhost:8888');
socket.on('data', function(message) {
text.innerHTML = message.data;
});
</script>
</body>
</html>
Instead of
parser.on('data', console.log);
Try this:
parser.on('data', function (data) {
io.emit('data', { data: data });
});
That should send the parsed data from the SerialPort to the socket, which should end up on the client side on the website.
Related
I tried to learn how to read static files with express from a reliable website. And then I found that not know why, my terminal tell me I'm success but website show me "Cannot Get /"(as following image show). I had found a lot of solution (e.g. in my html file, I add script src to socket.io) but still fail. Where can I start to deal with it? Please help me...
terminal show success
website show error
And the following is my code:
C:\...\1-on-1-webrtc\server.js
const express = require('express')
const app = express()
const http = require('http').createServer(app)
// static data
app.use('/', express.static(__dirname + '/public/'))
// TODO: Signaling
//start server listen 8080 port
http.listen(8080, () => {
console.log(`Server running in 8080`)
})
C:\...\1-on-1-webrtc\pubilc\index.html
(origin)
"hello"
(after)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>111</title>
<script src="https://cdn.socket.io/socket.io-3.0.5.js"></script>
</head>
<body>
<h1>"hello"</h1>
<script>
var socket = io();
</script>
</body>
</html>
I change Your code a little and here is my solution:
Firstly change your name of public folder to correct. Not "pubilc" only "public".
Folder & File Structure:
server.js :
const express = require("express");
const app = express();
const port = 8080;
// const http = require("http").createServer(app);
// static data
app.use("/", express.static(__dirname + "/public"));
//start server listen 8080 port
app.listen(port, () => {
console.log(`Server is listening at http://localhost:${port}`);
});
index.html (without any changes) :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>111</title>
<script src="https://cdn.socket.io/socket.io-3.0.5.js"></script>
</head>
<body>
<h1>"hello"</h1>
<script>
var socket = io();
</script>
</body>
</html>
Output :
Tested with: express 4.17.2 node 16.13.0 Linux Ubuntu 20.04 and Win10
I'm trying to use a restful service to access data that is posted to a MongoDB cluster. My problem is that I can't even connect to the service, the get request doesn't seem to be working. Console.log("test")is not reached and I'm met with a blank console, so I don't think the readystate is changing.
I've done a ton of troubleshooting and found that the link works on its own (https://RESTfulServiceExample.[REPL.IT USERNAME].repl.co/items) and displays the data when pasted into the search bar. I've also tried changing browsers and even compared to my friend's code which works and STILL I can't even seem to connect.
I'm sure it's just some dumb little mistake but I'm completely at a loss here so any help is MUCH appreciated!
File with get request. I edited out the username. 'item' is the name of the MongoDB cluster.
<html>
<head>
<script type="text/javascript">
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && this.status == 200) {
console.log("test"); //NOT REACHED
var responseObj = JSON.parse
(xhttp.responseText);
};
}
//PROBLEM HERE
xhttp.open("GET", "https://RESTfulServiceExample.[REPL.IT USERNAME].repl.co/items", true);
xhttp.send();
</script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js">
</script></head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;">
</div>
</body>
</html>
RESTful Service:
Index.js: (edited out username and password of mongodb.
var express = require('express'); // control-shift-S to bring up shell in repl.it and npm
install express / other packages
var app = express();
var port = 5000; // the port is automatically routed by the repl.it domain
mongoose = require('mongoose');
Item = require('./model/model.js');
bodyParser = require('body-parser');
mongoose.Promise = global.Promise; // for asynchronous callbacks
mongoose.connect('mongodb+srv://[USERNAME]:[PASSWORD]#cluster0.thmkp.mongodb.net/Pokemon?
retryWrites=true&w=majority');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./routes/routes'); //importing route
routes(app); //register the route
app.listen(port);
Routes.js
'use strict';
module.exports = function(app) {
var itemList = require('../controllers/controller');
app.route('/items')
.get(itemList.list_items)
.post(itemList.create_item);
app.route('/items/:id')
.get(itemList.get_item)
.put(itemList.update_item)
.delete(itemList.delete_item);
};
Try to change
if (this.readyState == 4 && this.status == 200) {
// your code block
}
trying to copy a simple example but still cannot parse json post request,
ideas?
looking in the borwser (firefox) network tab, I see the request with json params.
but the server log comes out empty.
client
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var man = {
name:'name',
fam:'familiy'
};
var xhttp = new XMLHttpRequest();
var url = "http://localhost:8080/";
xhttp.open("post", url, true);
xhttp.send(JSON.stringify(man));
</script>
<title>Json Test</title>
</head>
<body>
Json Test
</body>
</html>
server
//require the express nodejs module
var express = require('express'),
//set an instance of exress
app = express(),
//require the body-parser nodejs module
bodyParser = require('body-parser'),
//require the path nodejs module
path = require("path");
//support parsing of application/json type post data
app.use(bodyParser.json());
app.post('/', function(req, res){
res.setHeader('Content-Type', 'application/json');
console.log(req.body);
res.send("done");
});
//Start listen on port
const port = 8080;
app.listen(port);
console.log("Node js listen on port " + port + "...");
You are not setting Content-Type header with your AJAX request. Please change to the following.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var man = {
name:'name',
fam:'familiy'
};
var xhttp = new XMLHttpRequest();
var url = "http://localhost:8080/";
xhttp.open("post", url, true);
xhttp.setRequestHeader('Content-Type', 'application/json');
xhttp.send(JSON.stringify(man));
</script>
<title>Json Test</title>
</head>
<body>
Json Test
</body>
</html>
well....
I guess I forgot these as well (working now)
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, **POST**, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
I am new to Node.js and am unable to find a way to solve my issue. I have written a server using Node.js to serve a html webpage. The problem is that it wont display the images that are in the same folder. I am trying to serve my webpage as well as my images and css file. Any help would be appreciated.
Relevant code:
server:
var http = require('http');
var fs = require('fs');
const PORT = 8080;
function handleRequest(request, response) {
console.log(request.url);
var bool = 0;
var index = fs.readFileSync("index.html", {
encoding: "utf-8"
});
if(request.url == "/")
{
bool = 1;
response.end(index);
}
else if(request.url == "/index" || request.url == "/index.html")
{
bool = 1;
response.end(index);
}
else if(bool == 0)
{
response.statusCode = 404;
response.end("Not Found");
}
}
var server = http.createServer(handleRequest);
server.listen(PORT, function() {
console.log("Started server on http://localhost:%s", PORT)
});
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My Personal Webpage</title>
<link rel="stylesheet" href="index-css.css"/>
</head>
<body>
<h1>Welcome!</h1>
<p>My paragraph.</p>
<img src="/family.jpg" alt="Family" style="width:342px;height:513px;">
<img src="/Another.jpeg" alt="Another" style="width:500px;height:500px;">
</body>
</html>
I recommend use app.use(express.static(__dirname + '/FOLDER_NAME')) in order to expose a folder to serve static files to the client. Here is the documents about serving static files using express.
Edit: Here is a simple working example of serving a index.html using express
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
I have a running server with apache and Socket.IO. I'm trying to send and receive message using socket.io on my website.
This is the code of my server:
var fs = require('fs');
var hskey = fs.readFileSync('file.key');
var hscert = fs.readFileSync('file.crt');
var options = {
key: hskey,
cert: hscert
};
var app = require('https').createServer(options);
var io = require('/usr/local/lib/node_modules/socket.io').listen(app);
app.listen(8181);
io.sockets.on('connection', function (socket) {
socket.emit('serverMessage', 'Bienvenue master!');
socket.broadcast.emit('serverMessage', 'New user online');
});
And this is the webpage:
<!doctype html>
<html>
<head>
<title>Socket.io Test</title>
<script src="./socket.io.js"></script>
</head>
<body>
<script>
var socket;
var firstconnect = true;
function connect() {
if(firstconnect) {
socket = io.connect('https://secure.mysite.com:8181');
socket.on('serverMessage', function(data){ message(data); });
socket.on('connect', function(){ status_update("Connected to Server"); });
socket.on('disconnect', function(){ status_update("Disconnected from Server"); });
socket.on('reconnect', function(){ status_update("Reconnected to Server"); });
socket.on('reconnecting', function( nextRetry ){ status_update("Reconnecting in "
+ nextRetry + " seconds"); });
socket.on('reconnect_failed', function(){ message("Reconnect Failed"); });
firstconnect = false;
}
else {
socket.socket.reconnect();
}
}
function disconnect() {
socket.disconnect();
}
function message(data) {
document.getElementById('message').innerHTML += "<br>" + "Server says: " + data;
}
function status_update(txt){
document.getElementById('status').innerHTML = txt;
}
function esc(msg){
return msg.replace(/</g, '<').replace(/>/g, '>');
}
function send() {
socket.send('clientMessage', 'world');
};
</script>
<h1>Socket.io Test</h1>
<div><p id="status">Waiting for input</p></div>
<div><p id="message"></p></div>
<button id="connect" onClick='connect()'/>Connect</button>
<button id="disconnect" onClick='disconnect()'>Disconnect</button>
<button id="send" onClick='send()'/>Send Message</button>
</body>
</html>
Everything seems to work fine under Safari (websocket) and Opera (json pooling) but with Firefox and Chrome (websocket) I cannot send any message from the client to the server. Everything else is working, I can handshake, connect and gets server messages. I made allot of research but seems like I'm the only one with this problem.
Thanks for helping me!
I found the problem, I was using a different version of socket.io.js then the server side.
when you attach the socket.io module to express it intercepts the socket.io route.
So when you request "https://secure.mysite.com:8181/socket.io" it will respond with
"Welcome to socket.io."
So when you request the client side socket.io.js it comes directly from the socket.io module.
"https://secure.mysite.com:8181/socket.io/socket.io.js"
So If you wan't to mod the client side library you could create a modified copy and let express serve up the file, but as you update socketio through npm you'll have to bump up your modified copy as well manually.
if in FireFox you get this error - first check enabled or no proxy. and turnoff proxy if enabled.