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();
Related
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.
I'm trying to run my site on localhost with Node.js. It downloads, but the script specified in my index file does not work. Looking at the page sources it seems that my script file has turned into an exact copy of my index file. What could cause that?
Here's my code:
const http = require('http')
const fs = require('fs')
const port = 3000
const server = http.createServer(function(req, res) {
res.writeHead(200, { 'Content-Type': 'text/html'})
fs.readFile('index.html', function(error, data) {
if (error) {
res.writeHead(404)
res.write('Error: File not found')
} else {
res.write(data)
}
res.end()
})
})
server.listen(port, function(error) {
if (error) {
console.log('Something went wrong', error)
} else {
console.log('Server is listening on port ' + port)
}
})
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h1>Hi</h1>
<div id="words">*</div>
<script src="script.js"></script>
</body>
</html>
script.js
words.innerHTML += "1";
You don't have any logic to return different responses (e.g. based on the requested URL), so your server always responds with the index.html document, even when other resources are requested (like your script).
You can implement the logic yourself, or you can use existing software to do it. A very commonly used one is called express.
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 am new to node js and trying to simply serve a site containing both an html and css file. I have the below code written
var http = require('http');
var fs = require('fs');
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(fs.readFileSync('./style.css', {encoding: "utf8"}));
res.write(fs.readFileSync('./index.html', {encoding: "utf8"}));
res.end();
}).listen(3000);
console.log('server running # 3000');
This 'works' when I fire up the server meaning that I can see the site rendering while considering the css, but the css text gets written out at the bottom of my site like its embedded text inside a div tag. Can anyone explain why I am seeing this? Also since I am new to nodejs, any recommendations on serving css or JS files on my server would be greatly appreciated.
I have modified your code (which is working). Have a look at it:
var http = require('http');
var fs = require('fs');
http.createServer((req, res) => {
console.log(req.url)
if (req.url === "/") {
fs.readFile('index.html', (err, html) => {
if (err) {
throw err;
}
res.setHeader('Content-type', 'text/html');
res.write(html);
res.statusCode = 200;
res.end();
});
}
else if (req.url == '/style.css') {
res.setHeader('Content-type', 'text/css');
res.write(fs.readFileSync('style.css'));
res.end();
} else {
res.write("invalid request")
res.end();
}
}).listen(3000);
console.log('server running # 3000');
Here is the HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="/style.css" />
</head>
<body>
Hello
</body>
</html>
and style.css
body {
color: red;
}
You need to return your files based on your request. For example, in this scenario, the HTML file is requesting the server for /style.css, the server looks at the code and finds the block which deals with that request
else if (req.url == '/style.css') {
res.setHeader('Content-type', 'text/css');
res.write(fs.readFileSync('style.css'));
res.end();
}
And finally returns the file. I hope that helps.
Recommendation:
Use express.js (https://expressjs.com/).
It is really fast minimal and easy to use NodeJS routing framework which follows the MVC pattern. There are lots of resources on youtube and google for this framework.