I run this code and when I go to ws://localhost:1337 I get this error, how can I fix it?
(I tried different ways on the internet but none of them solved my problem)
error in chrome : crbug/1173575, non-JS module files deprecated.
import { createServer } from "http";
const PORT = 1337;
const server = createServer((request, response) => {
response.writeHead(200);
response.end('hello world,');
}).listen(PORT, () => console.log(`server listening on port ${PORT}`));
server.on('upgrade', (req, socket, head) => {
console.log({
req,
socket,
head
});
});
;[
"uncaughtException",
"unhandledRejection"
].forEach(event =>
process.on(event, (err) => {
console.error(`something bad happened: ${event}, msg:${err.stack || err}`);
})
);
<!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>Web Socket</title>
</head>
<body>
<!-- 1 -->
<p>Message</p>
<output id="messages"></output>
<script>
const messages = document.getElementById('messages');
// 2
const socket = new WebSocket('ws://localhost:1337');
// 3
socket.onopen = (event) => console.log('WebSocket is connected!');
//4
socket.onmessage = (msg) => {
const message = msg.data
console.log('I got a message!', message);
messages.innerHTML += `<br /> ${message}`;
}
// 5
socket.onerror = (error) => console.log(`WebSocket error`, error);
// 6
socket.onclose = (event) => console.log(`Disconnected from the WebSocket server`);
</script>
</body>
</html>
My JS code is in a file called server.mjs.
Related
I watched a tutorial to run node.js server for the very first time on your computer. Luckly I've created the server but got stck as I tried to show the html content on the exact same server.
This is my index.js file code -
const http = require("http");
const fs = require("fs");
const port = 8020;
const server = http.createServer((req, res) => {
res.writeHead(200, { "Contet-type": "text/html" });
fs.readFile("index.html", (err, data) => {
if (err) {
res.writeHead(404);
res.write("Error file not found");
} else {
res.writeHead(data);
}
res.end();
});
});
server.listen(port, function (err) {
if (err) {
console.log("Something went wrong");
} else {
console.log("server listening on port " + port);
}
});
And this is what I'm getting in the terminal -
PS C:\Users\Dell\OneDrive\Desktop\New folder> node index.js
server listening on port 8020
node:_http_server:343
throw new ERR_HTTP_INVALID_STATUS_CODE(originalStatusCode);
^
RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: <!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>Document</title>
</head>
<body>
<h1>This is my first nodeJs project</h1>
</body>
</html>
at new NodeError (node:internal/errors:393:5)
at ServerResponse.writeHead (node:_http_server:343:11)
at C:\Users\Dell\OneDrive\Desktop\New folder\index.js:12:11
at FSReqCallback.readFileAfterClose [as oncomplete] (node:internal/fs/read_file_context:68:3) {
code: 'ERR_HTTP_INVALID_STATUS_CODE'
}
Node.js v18.12.1
PS C:\Users\Dell\OneDrive\Desktop\New folder>
And not even the localhost, which is 8020 in this case, is not running on the browser.
I just want to know the mistakes here that I'm totally unaware with or something that I need to do in order to have my desired output.
You're writing the HTML to the header of the response:
res.writeHead(data);
you want:
res.end(data);
or
res.write(data);
res.end();
I'm new to Node.js and I'm just trying to create simple web server that can serve HTML, JS, and CSS files.
The server works and I can view index.html in localhost. But I can't seem to link the request.js to index.html. Here's my project structure:
--public
----js
------request.js
----index.html
--app.js
app.js
const http = require("http");
const fs = require('fs').promises;
const host = 'localhost';
const port = 8000;
const requestListener = function (req, res) {
fs.readFile(__dirname + "/public/index.html")
.then(contents => {
res.setHeader("Content-Type", "text/html");
res.writeHead(200); // success status code
res.end(contents);
})
.catch(err => {
res.writeHead(500);
res.end(err);
return;
});
};
const server = http.createServer(requestListener);
server.listen(port, host, function(error) {
if (error) {
console.log('Something went wrong', error)
}
else {
console.log(`Server is running on http://${host}:${port}`);
}
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<script src="/js/request.js" defer></script>
<title>Water Web Dev</title>
<body>
</body>
</html>
</head>
request.js
const axios = require('axios');
const getBtn = document.getElementById('get-btn');
const getData = () => {
axios.get('https://reqres.in/api/unknown')
.then(function (response) {
// success
console.log(response);
})
.catch(function (error) {
// error
console.log(error);
})
.then(function () {
// always executed
});
}
getBtn.addEventListener('click', getData)
You should server your css & js files as static files.
I am new to this area so forgive me if I fail to explain my question well.
I am essentially trying to send a string "Hello, I connected to the port" to my Javascript client, only when I have pressed a HTML button.
FOR TESTING PURPOSES:
I have been successful in running a client and server Javascript socket connection, and can receive data back and forth. However when trying to link this to my html page I fail to connect them and send data.
CLIENT.JS:
const net = require('net');
const client = net.createConnection({ port: 9898 }, () => {
console.log('CLIENT: I connected');
client.write('CLIENT: Hello this is client!');
});
client.on('data', (data) => {
console.log(data.toString());
client.end();
});
client.on('end', () => {
console.log('CLIENT: I disconnected from the server.');
});
SERVER.JS
const net = require('net');
const server = net.createServer((socket) => {
socket.on('data', (data) => {
console.log(data.toString());
});
socket.write('SERVER: Hello! \n');
socket.end('SERVER: Closing connection now \n');
}).on('error', (err) => {
console.error(err);
});
server.listen(9898, () => {
console.log('opened server on', server.address().port);
});
if you save the above code and run them using the lines:
node server.js
node client.js
You will find that they send messages between them quite nicely.
The issue starts when I try to run my html page (which is served using node.JS on port 8083)
(I server my HTML page using npx http-server --cors)
An approach I tried was to place the code in client.js into a function and then call it in my html button:
<input type = "button" onclick = "outputData()" value = "Display">
(outputData being the function that contains the code in client server)
I'm not sure if its even something that can be done, but I'd like to essentially start my server.js from my HTML page, when a button is clicked, so that it can begin sending the data. I'd want to run "node client.js" on terminal and see that messages are coming through as server.js would have been started from my webpage
Any advice would be highly appreciated. Thank you for taking the time.
Information about socket.io library, https://socket.io/docs/v3/client-api/index.html
Sending message index.html
<html>
<body>
<input type="button" onclick="javascript:sendMessage()" value="Click here"/>
<script>
const sendMessage = () => {
var new_message = {message: "this is my message"}
socket.emit('new_message', new_message);
}
</script>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io("http://localhost:8080");
</script>
</body>
</html>
server.js
socket.on('new_message', (data) => {
var New_Details = {
message: data.message
};
socket.broadcast.emit('update_message', New_Details);
console.log(data.username + ' just wrote ' + data.message);
});
I managed to solve this by using Websockets. Where my webserver acted as the client, and I adjusted my server.js to the following:
SERVER.JS
const WebSocket = require("ws");
const wss = new WebSocket.Server({ port: 9898 });
wss.on("connection", ws => {
console.log("New client connected!");
ws.on("message", data => {
console.log(`Client has sent us: ${data}`);
ws.send(data.toUpperCase());
});
ws.on("close", () => {
console.log("Client has disconnected!");
});
});
HTML
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/assets/dcode.css">
<link rel="shortcut icon" href="/assets/favicon.ico" type="image/x-icon">
<title>WebSockets</title>
</head>
<body>
<script>
const ws = new WebSocket("ws://localhost:9898");
ws.addEventListener("open", () => {
console.log("We are connected!");
ws.send("Hey, how's it going?");
});
ws.addEventListener("message", ({ data }) => {
console.log(data);
});
</script>
</body>
</html>
I want to be able to write functions in multiple .js files and use the same socket that is create in my main server.js
server.js:
var express = require('express')
var app = express()
var http = require('http')
var server = http.createServer(app)
var io = require('socket.io')(server)
var GOR = require('./gor')
var path = require('path');
app.use(express.static(path.join(__dirname, '/public')));
//handles get request and serves index.html
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});
//wait for server to start
server.listen(8080,()=>{
console.log("server started");
setInterval(emit_data,5000);
emit_data();
//setInterval(GOR.send_from_another_js,5000);
//GOR.send_from_another_js(io);
})
function emit_data(){
io.emit( 'update', "webserver.js");
}
As you can see from the code above, I have a function that emits to socket every 5 seconds and that works fine. I have confirmed it already.
All I want to do now, is to create a seperate.js file and keep all my functions there to make the code look cleaner. I name another .js file gor.js:
gor.js:
//I want to call this function in my webserver.js and transmit this socket
function send_from_another_js(io){
console.log("function called");
io.emit( 'update', "another_js");
}
module.exports = {
send_from_another_js
}
When I call this function in my server.js , it does not work:
server.listen(8080,()=>{
console.log("server started");
setInterval(GOR.send_from_another_js,5000);
GOR.send_from_another_js(io);
})
What is correct way to use the same .io in other .js files? The above does not work.
EDIT1
In my .html, I wait for a message on socket:
window.addEventListener('DOMContentLoaded', () => {
socket.on('update', function(number_to_set) {
console.log("socket update received");
document.getElementById('number1').innerHTML = number_to_set;
});
var button = document.getElementById("operation_code_button");
button.addEventListener("click", function(event){
var val = document.getElementById("operation_code_input").value;
console.log("socket clicked, emmiting data");
socket.emit('button_click',val);
});
})
And in my .js file I emit to this socket every 5 seconds:
server.listen(8080,()=>{
console.log("server started");
setInterval(emit_data,5000);
emit_data();
})
After 5 seconds, I can see that my webpage update data so everything works!!!
I want to declare the emit_data function inside another .js file and use it in my main .js file.
The function in my secondary .js file ( gor.js):
function send_from_another_js_1(io){
io.emit( 'update', data);
}
I want to call it in my main .js the same way I call emit_data
You need to wait for your server to get initialized. You are calling your function before socket.io is ready. That's why io.emit function is 'undefined'.
server.listen(8080,()=>{
GOR.send_from_another_js(io);
})
Edited:(3)
Trust it is what you are looking for...
"server.js"
const content = require('fs').readFileSync(__dirname + '/index.html', 'utf8');
const httpServer = require('http').createServer((req, res) => {
// serve the index.html file
res.setHeader('Content-Type', 'text/html');
res.setHeader('Content-Length', Buffer.byteLength(content));
res.end(content);
});
const io = require('socket.io')(httpServer);
const apple = require("./File2.js")
apple.send_from_another_js_1(io);
apple.send_from_another_js_2(io);
var port = 3000; //wamp server
var prompt = 'Open browser at http://localhost:'
httpServer.listen(port, () => {
console.log(prompt, port);
});
"File2.js"
function send_from_another_js_1(io){
io.on('connection', function (socket) {
socket.on('file2_1_EventTrigged', function (data) {
socket.emit('update1', "send_from_another_js_1(io) : "+ data);
console.log("+++ function send_from_another_js_1(io) called");
});
});
}
function send_from_another_js_2(io){
io.on('connection', function (socket) {
socket.on('file2_2_EventTrigged', function (data) {
socket.emit('update2', "send_from_another_js_2(io) : "+ data);
console.log("... function send_from_another_js_2(io) called");
});
});
}
module.exports = {
send_from_another_js_1,
send_from_another_js_2
}
"index.html"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Content-Type" content="text/html">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="keywords" content="HTML, CSS, JavaScript">
<meta name="author" content="Dr.Chaiya Tantisukarom">
<meta http-equiv="Cache-Control" content="public, max-age=31536000">
<title>NodeJS socket.io</title>
</head>
<body>
<h1 style="text-align: center;">Hello another world</h1>
<div style="text-align: center;">
<span>
<button onclick="file2_1()">file2_1</button>
</span>
<span>
<button onclick="file2_2()">file2_2</button>
</span>
</div>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('connect',()=>{
//alert('Connected');
})
function file2_1(){
socket.emit('file2_1_EventTrigged', "Hello file2_1, how are you today?");
}
socket.on('update1', (data)=>{
alert(data);
})
function file2_2(){
socket.emit('file2_2_EventTrigged', "Hi file2_2, trust you are ok.");
}
socket.on('update2', (data)=>{
alert(data);
})
</script>
</body>
</html>
Cheers !!!
When you call this:
server.listen(8080,()=>{
console.log("server started");
setInterval(GOR.send_from_another_js,5000);
GOR.send_from_another_js(io);
})
setInterval() isn't providing a parameter for GOR.send_from_another_js(), so io becomes undefined.
To fix this, I would use a second lambda expression inside of your setInterval() call.
server.listen(8080, () => {
console.log("server started");
setInterval(() => {
GOR.send_from_another_js(io);
}, 5000);
GOR.send_from_another_js(io);
});
I'm trying to get the most basic thing possible to work and can't figure out what I'm doing wrong.
my html file:
<!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">
<script type="text/javascript" src="script.js"></script>
<title>This Is Just a Dummy App</title>
</head>
<body>
<button onclick="makeAlert()">Click here</button>
</body>
</html>
script.js, it's in the same directory as the HTML file
const makeAlert = () => { alert('Hey hey') };
The page does not want to load, period and there are no errors in the browser console.
UPDATE
This is part of Node.js app, without Express or anything and this is how it's configured to load HTML. I don't know if this is a factor here or not.
const http = require('http');
const fs = require('fs');
const hostname = '127.0.0.1';
const port = 3001;
const server = http.createServer((req, res) => {
const url = req.url;
if(url === '/') {
res.writeHead(200, {
'Content-Type': 'text/html'
});
fs.readFile('./index.html', null, function (err, data) {
if (err) {
res.writeHead(404);
res.write('something went wrong');
} else {
res.write(data)
}
res.end();
})
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Works fine from a snippet, are you trying to run it from a server or just from the file system? Some browsers don't like running scripts from the file system. Get a development web server.
const makeAlert = () => { alert('Hey hey') };
<!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">
<title>This Is Just a Dummy App</title>
</head>
<body>
<button onclick="makeAlert()">Click here</button>
</body>
</html>