I'm new programmer to node.js. I trying to create vanilla server in node.js. In my client, I used ES6 modules. when I start my server and search for http://localhost:3000/ in my browser, HTML and CSS loaded but for javascript have this error:
I have four javascript modules for client side and in HTML I use this code for load javascript moduls:
<script type="module" src="js/controller.js" async></script>
My server code :
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = 3000;
const server = http.createServer();
server.on('request', (req, res) => {
let routes = {
'GET': {
'/': indexHtml,
}
}
console.log(req.url)
let handler = routes[req.method][req.url];
handler = handler || readFile;
handler(req, res);
})
server.listen(PORT, () => {
console.log(`Listening on port ${PORT}...`)
});
function indexHtml(req, res) {
readFile({ url: '/index.html' }, res);
}
function readFile(req, res) {
var filePath = path.join(__dirname, '../client/', req.url);
// console.log(filePath)
fs.readFile(filePath, (error, data) => {
if (error) {
res.writeHead(404);
res.write('Not found error 404');
res.end()
} else {
res.writeHead(200);
res.write(data);
res.end();
}
})
}
How can I solve this error and serve javascript modules, Thanks a lot for your help.
With comment #derpirscher, I change my reader function with this code :
function readFile(req, res) {
var filePath = path.join(__dirname, '../client/', req.url);
fs.readFile(filePath, (error, data) => {
if (error) {
res.setHeader('Content-Type', 'text/html');
res.writeHead(404);
res.write('Not found error 404');
res.end()
} else {
const url = req.url === '/' ? '/index.html' : req.url;
if (req.url.includes('js')) res.setHeader('Content-Type', 'application/javascript');
if (req.url.includes('css')) res.setHeader('Content-Type', 'text/css');
if (req.url.includes('html')) res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.write(data);
res.end();
}
})
}
Related
This question already has an answer here:
Link index.html client.js and server.js
(1 answer)
Closed 10 months ago.
I am trying to write a web server application for my Frontend.
The structure is for the fronted files is :
Backend
server.js
Fronted
Index
Javascript
index.js
style.css
index.html (it is outside of Frontend folder)
The code for server.js is:
const fs = require('fs');
const port = 5000;
const server = http.createServer(function (request, response) {
fs.readFile('../Frontend/index.html', function (error, data) {
response.setHeader( "Content-Type", "text/html");
if (error) {
response.writeHead(404);
response.write('Error: File Not Found');
} else {
response.write(data);
}
response.end();
})
})
server.listen(port, function (error) {
if (error) {
console.log('Something went wrong ', error);
} else {
console.log('Server is listening on port ' + port);
}
});
When I try to access localhost:5000 the HTML code shows, but without CSS, js or images, but when I am looking in the console at the network all the files are there (index.js, style.css, the images);
You can achieve the results you want as follows:
const fs = require('fs');
const port = 5000;
const http = require('http');
const server = http.createServer( function (request, response) {
let filePath = '.'+request.url; //assumes your static files are
// placed in the root directory
if(request.url ==='/' ||request.url==='/index.html'){
filePath = './index.html';
fs.readFile(filePath, function (error, data) {
response.setHeader('Content-Type', 'text/html');;
if (error) {
response.writeHead(404);
response.write('Error: File Not Found');
}
response.end(data,'utf-8');
})
} else if(request.url==='/index.css'){
filePath = './index.css';
fs.readFile(filePath, function (error, data) {
response.setHeader('Content-Type', 'text/css');;
if (error) {
response.writeHead(404);
response.write('Error: File Not Found');
}
response.end(data,'utf-8');
})
} //maybe some additional else if for image and so on or you can improve
//this logic but anyway this code gives you the right direction
})
server.listen(port, function (error) {
if (error) {
console.log('Something went wrong ', error);
} else {
console.log('Server is listening on port ' + port);
}
});
I just set up my first node HTTP server, and I am trying to get the response data from a JSON file in my application. When I declare a JSON object in the server.js file, all works well.
data = "{"sample json" : "this is a test"}";
But I want to replace data with a static JSON file at data/sample.json
Here's an example in my server.js file
const http = require("http");
const hostname = "localhost";
const port = 3000;
const server = http.createServer(function(req, res) {
data = // this is where I want to get the JSON data from data/sample.json
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(data);
res.end();
});
Solved with fs.readFile()
const http = require("http");
const hostname = "localhost";
const port = 3000;
const fs = require('fs');
const server = http.createServer(function(req, res) {
filePath = './data/sample.json';
if (req.path == '/data/sample.json') {
fs.readFile(filePath, function(error, content) {
if (error) {
if (error.code == 'ENOENT') {
response.writeHead(404);
response.end(error.code);
}
else {
response.writeHead(500);
response.end(error.code);
}
}
else {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(content);
}
});
}
else {
response.writeHead(404);
response.end('restricted path');
}
});
In case someone else tumbles upon this question. The answer above has ton of typos and errors and incomplete. Here is a working solution.
const http = require("http");
const hostname = "localhost";
const fs = require('fs');
const port = 8080;
const server = http.createServer(function(req, res) {
filePath = './data/sample.json';
if (req.url == '/api/data') {
fs.readFile(filePath, function(error, content) {
if (error) {
if (error.code == 'ENOENT') {
res.writeHead(404);
res.end(error.code);
}
else {
res.writeHead(500);
res.end(error.code);
}
}
else {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(content);
}
});
}
else {
res.writeHead(404);
res.end('404 NOT FOUND');
}
});
server.listen(port, hostname, () => {
console.log('Server started on port ', port);
});
I cant understand how and where to use response.end(). i get it working when loading only single response but when i try to load (say) two html files (index and form in my case) , the server does not load anything.
if i put res.end() after loading the index html it works but server closes.
var http = require('http');
var formidable = require('formidable');
var url=require('url');
var path=require('path');
var fs=require('fs');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
filepath=path.join(__dirname,'index.html');
fs.readFile(filepath,null,function(err,data){
if(err){
res.writeHead(404);
res.write(err+" Error");
}
else{
res.write(data);
}
res.end();
});
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function () {
res.write('File uploaded');
res.end();
});
} else {
var q=url.parse(req.url,true);
var filename=path.join(__dirname,q.pathname);
console.log(filename);
fs.readFile(filename,function(err,data){
if (err) {
res.writeHead(404);
res.write(err+"404 Not Found");
}
else{
res.write(data);
}
res.end();
})
}
}).listen(8080);
Other tips on improving code is much appreciated :)
var http = require('http');
var formidable = require('formidable');
var url = require('url');
var path = require('path');
var fs = require('fs');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function () {
res.write('File uploaded');
res.end();
});
} else if (req.url.length > 1) {
var q = url.parse(req.url, true);
var filename = path.join(__dirname, q.pathname);
console.log(filename);
fs.readFile(filename, function (err, data) {
if (err) {
res.writeHead(404);
res.write(err + "404 Not Found");
}
else {
res.write(data);
}
res.end();
})
} else {
filepath = path.join(__dirname, 'index.html');
fs.readFile(filepath, null, function (err, data) {
if (err) {
res.writeHead(404);
res.write(err + " Error");
}
else {
res.write(data);
}
res.end();
});
}
}).listen(8080);
below node.js code is using express to route to different urls, how can I do the same with http instead of express?
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/', function (req, res) {
res.send('Welcome Home');
});
app.get('/tcs', function (req, res) {
res.send('HI RCSer');
});
// Handle 404 - Keep this as a last route
app.use(function(req, res, next) {
res.status(404);
res.send('404: File Not Found');
});
app.listen(8080, function () {
console.log('Example app listening on port 8080!');
});
Here's a quick example. Obviously, there are many ways of doing this, and this is probably not the most scalable and efficient way, but it will hopefully give you an idea.
const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
req.on('error', err => {
console.error(err);
// Handle error...
res.statusCode = 400;
res.end('400: Bad Request');
return;
});
res.on('error', err => {
console.error(err);
// Handle error...
});
fs.readFile('./public' + req.url, (err, data) => {
if (err) {
if (req.url === '/' && req.method === 'GET') {
res.end('Welcome Home');
} else if (req.url === '/tcs' && req.method === 'GET') {
res.end('HI RCSer');
} else {
res.statusCode = 404;
res.end('404: File Not Found');
}
} else {
// NOTE: The file name could be parsed to determine the
// appropriate data type to return. This is just a quick
// example.
res.setHeader('Content-Type', 'application/octet-stream');
res.end(data);
}
});
});
server.listen(8080, () => {
console.log('Example app listening on port 8080!');
});
Try the code below . It is a pretty basic example
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'}); // http header
var url = req.url;
if(url ==='/about'){
res.write('<h1>about us page<h1>'); //write a response
res.end(); //end the response
}else if(url ==='/contact'){
res.write('<h1>contact us page<h1>'); //write a response
res.end(); //end the response
}else{
res.write('<h1>Hello World!<h1>'); //write a response
res.end(); //end the response
}
}).listen(3000, function(){
console.log("server start at port 3000"); //the server object listens on port 3000
});
express can also be used by http directly.
From: https://expressjs.com/en/4x/api.html#app.listen
The app returned by express() is in fact a JavaScript Function, designed to be passed to Node’s HTTP servers as a callback to handle requests.
var http = require('http')
var express = require('express')
var app = express()
http.createServer(app).listen(80)
With this, you can still make use of express for routing, while keeping native http support.
I wrote a very simple program to demonstrate request handling in Node (actually following a tutorial), but the server seems to take forever to respond to the GET / request. Here's the code I'm using:
const http = require('http');
const url = require('url');
let routes = {
'GET': {
'/': (req, res) => {
res.writeHead(200, {'Content-type': 'text/html'});
res.end('GET /');
}
},
'POST': {
},
'NA': (req, res) => {
res.writeHead(404);
res.end('Content not found');
}
}
function router(req, res) {
let baseURI = url.parse(req.url, true);
// the function that gets resolved and used to handle the request
let resolveRoute = routes[req.method][baseURI.pathname];
}
http
.createServer(router).listen(3001, () => {
console.log('Listening on port 3001');
});
Something I'm doing wrong?
Found it myself.
I was resolving the handler function but not calling it. Adding resolveRoute(req, res); to the end of the router() function makes it work. :)