I'm trying to add CSS to my HTML using express() function in localhost:3000 by Node.js.
Unfortunately, something is weird. I followed the steps from tutorial step by step but still my css doesn't load. My style.css is in css folder (css/style.css). Here is my code:
app.js (note that I used app and app1)
var app = require('http').createServer(handler);
var io = require('socket.io').listen(app);
var fs = require('fs');
var express = require('express');
var app1 = express();
var mySocket = 0;
app1.use(express.static('/css'));
app.listen(3000); //Which port are we going to listen to?
function handler (req, res) {
fs.readFile(__dirname + '/index.html', //Load and display outputs to the index.html file
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
console.log('Webpage connected'); //Confirmation that the socket has connection to the webpage
mySocket = socket;
});
//UDP server on 41181
var dgram = require("dgram");
var server = dgram.createSocket("udp4");
server.on("message", function (msg, rinfo) {
console.log("Broadcasting Message: " + msg); //Display the message coming from the terminal to the command line for debugging
if (mySocket != 0) {
mySocket.emit('field', "" + msg);
mySocket.broadcast.emit('field', "" + msg); //Display the message from the terminal to the webpage
}
});
server.on("listening", function () {
var address = server.address(); //IPAddress of the server
console.log("UDP server listening to " + address.address + ":" + address.port);
});
server.bind(41181);
style.css (css/style.css)
.test
{
color:red;
}
index.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<link rel="stylesheet" type="text/css" href="/css/style.css" />
</head>
<body>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('field', function (data) {
console.log(data);
$("#field").html(data);
});
</script>
<div class='test'>Data from C#: </div><div id="field"></div>
</body>
</html>
You set the root of the static module to /css here
app1.use(express.static('/css'));
but then you request /css/style.css which means express looks for the file in /css/css/style.css (note that this path is absolute and not relative to your project).
Put everything in a public folder, e.g. public/css/style.css and then
app1.use(express.static(__dirname + '/public'));
Edit: Here's a minimal working example which serves the index.html and the style.css (in public/css/style.css)
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.get('/index.html', function(req, res, next) {
res.sendFile(__dirname + '/index.html');
});
app.listen(3000);
Related
I've been having this issue for the past 6 or so hours and I can't figure it out. I followed examples perfectly, yet when I run my server, the console.log output does not get displayed on the html page. This is my first time messing with Node.js. Here is the code:
Server:
require('dotenv').config()
var Twitter = require ('twitter');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io').listen(app);
var port = process.env.PORT || 8000;
var express = require ('express');
var events = require('events')
var eventEmitter = new events.EventEmitter();
// add API keys to .env file. .env_sample for details
var T = new Twitter({
consumer_key: process.env.CONSUMER_KEY,
consumer_secret: process.env.CONSUMER_SECRET,
access_token_key: process.env.ACCESS_TOKEN_KEY,
access_token_secret: process.env.ACCESS_TOKEN_SECRET
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.use(express.static(__dirname + '/public'));
eventEmitter.on('logging', function(message) {
io.emit('log_message', message);
});
http.listen(port, function(){
console.log('listening on *:' + port);
});
// Override console.log
var originConsoleLog = console.log;
console.log = function(data) {
eventEmitter.emit('logging', data);
originConsoleLog(data);
};
// code for test.
setInterval(function() {
console.log('X: ' + Math.random());
}, 2000);
/*T.get('statuses/home_timeline', function(error, tweets, response) {
if(error) throw error;
tweets.render
console.log(tweets); // General Tweet Timeline
});*/
HTML:
<!doctype html>
<html lang = "eng">
<head>
<meta charset="UTF-8">
<title> Twitter Client</title>
<link rel="stylesheet" type = "text/css" href="/css/index.css">
</head>
<body>
<img class="logo" src="/images/Twitter_Logo_Blue.png" height = "250" width = "250" alt="blue_bird">
<h1> Using this simple twitter client, the user can view general tweets, specify a specific twitter handle, and search tweets by text. </h1>
<ul id = "messages"></ul>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function(){
var socket = io();
socket.on('log_message', function(msg){
$('#messages').append($('<li>').text(msg));
});
});
</script>
</body>
</html>
For the life of me I can't figure out what's going on, and this project is due shortly. Any help would be GREATLY appreciated.
I send 1 by serialport on arduino to web by node and socket.io. The problem is that when I send the data I have:
Data: [object Object]
Data: [object Object]
...
but I want something like that
Data: 1
Data: 1
...
There is no value "1", I try to send string and still the same. Why is that?
Program works ok but this value problem is wall for me to go further I have a message in console:
userk#user-k52j:~/sio$ node app.js
http.listen
Port OPEN.
express deprecated res.sendfile: Use res.sendFile instead app.js:10:9
Socket.io connected.
But when I change sendfile to sendFile the program crash.
This is my programs:
Arduino:
void setup(){Serial.begin(9600);}
void loop(){
Serial.println(1);
delay(2000);
}
app.js
var app = require("express")();
var express = require("express");
app.use(express.static(__dirname + '/public'));
var http = require("http").Server(app);
var io = require("socket.io")(http);
app.get("/", function(req, res){
res.sendfile("index.html");
});
var mySocket;
// Obsługa portu szeregowego
var SerialPort = require("serialport").SerialPort;
var mySerial = new SerialPort("/dev/ttyUSB0", {
baudrate: 9600,
});
mySerial.on("open", function(){
console.log("Port OPEN.");
});
mySerial.on("data", function(data){
//console.log("Data: " + data + 'ls/n');
io.emit("dataArduino",{
valor: data
});
});
mySerial.on("error", function(error){
console.log("Failed to open: " + error);
});
io.on("connection", function(socket){
console.log("Socket.io polaczony.")
});
http.listen(3000, function(){
console.log("http.listen");
});
index.html
<!doctype html>
<html lang="pl">
<head>
<meta charset="utf-8">
<title>Arduino node.js test</title>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<script type="text/javascript">
var socket = io();
socket.on("dataArduino", function(data){
console.log(data);
document.write("Data: "+ data + "<br />");
});
</script>
</body>
</html>
so as said above, i run the html file only and i'm able to see the pictures, but when i run the file via node it sends me a 404 error on the file i used.
<html>
<body>
<img src="aaa.jpg" />
<script src="/socket.io/socket.io.js">
</script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
</script>
</body>
</html>
and the node code
var app = require("express")();
var http = require("http").Server(app);
var io = require("socket.io")(http);
app.get("/", function (req, res) {
res.sendFile(__dirname + "/Movie.html");
});
http.listen(5969, function () {
console.log("Server Open");
});
how can i stop this from happening?
To serve static files such as images and scripts, you need to include a middleware that serves static files. Put all your static files inside of a public directory and serve them like this.
var express = require("express");
var app = express();
var http = require("http").Server(app);
var io = require("socket.io")(http);
// Serve static files
app.use(express.static(__dirname + '/public'));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/Movie.html");
});
http.listen(5969, function () {
console.log("Server Open");
});
i am accessing the script.js and libs.js in index.html like this:
<body style='margin:0px' >
<canvas id='your_canvas'
style='position: absolute; background-color: black;'></canvas>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="/libs.js"></script>
<script type="text/javascript" src="/script.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function($){
main(); //this function is inside of script.js
});
</script>
but the .js files cannot be accessed and showing error:
1) GET script.js 404 (Not Found) localhost/:12.
2) GET libs.js 404 (Not Found) localhost/:11.
3) Uncaught ReferenceError: main is not defined (index):17.
where am i going wrong and how can i include these two JavaScript files using node.js?
my app.js is :
var express = require("express"),
app = express(),
server = require("http").createServer(app),
io = require("socket.io").listen(server);
server.listen(8000);
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
app.use(express.static(__dirname + '/public/script.js'));
app.use(express.static(__dirname + '/public/libs.js'));
io.sockets.on('connection', function(socket) {
socket.on('send coordinates',function(data){
io.sockets.emit('coordinates', data);
});
});
and then i have my script.js and libs.js files.
You need to actually serve these files if you want them to be accessible. You can't just include them in your project directory. If you are using Express, you can designate a static file directory like this:
app.use(express.static(__dirname + '/public'));
You can also use node-static or even create a handler for each file...
Using express, your code should look something like this (Not tested):
var express = require("express");
var app = express();
app.server = require('http').createServer(app);
var io = require("socket.io").listen(app.server);
app.get('/', function(req, res){
res.sendfile(__dirname + '/public/index.html'); // I would move this file to public
});
app.use(express.static(__dirname + '/public'));
io.sockets.on('connection', function(socket) {
socket.on('send coordinates',function(data){
io.sockets.emit('coordinates', data);
});
});
app.server.listen(8000);
Are you trying to call:
<script>
jQuery(function($){
main(); //this function is inside of script.js
});
</script>
If you are then you need to save your code as a file named script.js in the root directory. Adding javascript/jQuery between tags in your html does not need to be called and will run automatically.
I'd advise laying your script out in the following way too, i don't recognize the way you have laid it out.
<script>
var main = function() {
\\Your javascript/jQuery
}
$(document).ready(main);
</script>
Hello guys i'm having a problem in redis pub/sub because my client does not show the message i've published in redis-cli. I used the codes found here in stackoverflow and i made some modification. Here is the link and code. I hope you can help me, my goal is to publish the message to the client index.html using redis publish in redis-cli. I've done this before but i can't make it work again. Thanks in advance guys.
Here is my client index.html
<html>
<head>
<title>PubSub</title>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<!-- <script src="/javascripts/socket.js"></script> -->
</head>
<body>
<div id="content"></div>
<script>
var socket = io.connect('http://localhost:3000');
var content = $('#content');
socket.on('connect', function() {
});
socket.on('message', function (message){
content.prepend(message + '<br />');
}) ;
socket.on('disconnect', function() {
console.log('disconnected');
content.html("<b>Disconnected!</b>");
});
socket.connect();
});
</script>
</body>
</html>
Here is my server.js
var express = require('express');
var app = express();
var redis = require('redis');
var http = require('http');
var server = http.createServer(app);
var socket = require('socket.io').listen(server);
var publish = redis.createClient();
app.listen(3000);
console.log("Express server listening on port 3000")
app.get('/', function (req,res) {
res.sendfile(__dirname + '/public/index.html');
});
socket.on('connection', function (client) {
var subscribe = redis.createClient();
subscribe.subscribe('pubsub');
subscribe.on("message", function (channel, message) {
publish.send(message);
});
publish.on('message', function (msg) {
});
publish.on('disconnect', function() {
subscribe.quit();
});
});
Redis will not send data to connected clients for you. You must instruct Socket.IO to emit data:
subscribe.on("message", function (channel, message) {
socket.emit('message', message);
});