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);
}
});
Related
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'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();
}
})
}
I am building an API that uses socket connection to interact with a server backend built in C#. This is what I have so far
const request = require('request');
const express = require('express');
const app = express();
var server = require('http').createServer(app);
var cors = require("cors");
app.use(cors());
const net = require('net');
const client = new net.Socket();
const stringToJson=require('./stringToJson')
const port = process.env.PORT;
const host = process.env.HOST;
client.keepAlive=true
client.on('close', function() {
console.log('Connection closed');
});
app.get('/getScores',function (req,res) {
let dataSend=''
client.on('data', function (data) {
console.log('Server Says : ' + data);
if(data!='ANALYSIS-ERROR'){
dataSend=stringToJson.stringToJson(data)
}
else{
dataSend=stringToJson.stringToJson('0:0.0:0.0:0.0:0:0:0.0:0.0:0.0:0.0:0.0:0:0.0:0.0:0.0:0.0:0.0:0:0.0:0.0:0.0:0.0:0.0:0:0.0:0.0:0.0:0.0:0.0')
}
client.destroy()
return res.send(dataSend)
});
client.connect(port, host, function () {
client.write(`GENERAL-ANALYSIS|${req.query.id}|${req.query.website}|`)
return
});
return
})
app.get('/getPlace',function (req,res) {
console.log(req.query)
request(
{ url: `https://maps.googleapis.com/maps/api/place/textsearch/json?query=${req.query.name}+in+${req.query.city}&key=${process.env.API_KEY}` },
(error, response, body) => {
if (error || response.statusCode !== 200) {
return res.status(500).json({ type: 'error', message: error.message });
}
return res.json(JSON.parse(body));
}
)
})
//TODO ADD 404 500 PAGES
app.use((req, res, next) => {
res.status(404).send("Sorry can't find that!");
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
server.listen(9000, () => {
console.log(`App running at http://localhost:9000`);
});
Basically it creates a connection with the server and listens for some data to be sent back. Then processes the string and sends it to the React frontend. The api calls are made by the frontend using axios
It works but if you refresh the page it throws this error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
How do I fix this?
Try setting the headers as found in the documentation request.setHeader(name, value)
request.setHeader('Content-Type', 'application/json');
Sorry guys, I'm kind of lost. How can I console.log response.statusCode when piping?
var express = require('express');
var path = require('path');
var request = require('request');
var fs = require('fs');
var app = express();
var port = 8000;
var destination = fs.createWriteStream('./downloads/google.html');
var url = "http://www.google.com/";
request(url).pipe(destination)
.on("finish", function() {
console.log("done");
console.log(response.statusCode); // <<<<<<<<<<<<<<<<<<<<<<<<<<<< this
})
.on("error", function(err){
console.log(err);
});
app.listen(port, function(){
console.log('running server on ' + port);
});
You need to catch the response event from request. It won't be in the finished event from the pipe. You should also consider catching errors before the pipe. This is where you'll catch network errors. After the pipe you'll catch file errors.
request(url)
.on('response', function(response) {
console.log(response.statusCode) // <--- Here 200
})
.on("error", function(err){
console.log("Problem reaching URL: ", err);
})
.pipe(destination)
.on("finish", function(response) {
console.log("done");
})
.on("error", function(err){
console.log("Problem writing file: ", err);
});
I have an excel file. I want to reply excel file as a stream to the user using hapi JS reply object. I tried like this but it didn't work.
let readStream = fs.createReadStream(filePath);
reply(null,readStream.pipe());
Could anyone suggest me an approach to achieve this?
Use this code for serving file . If files are static files it prints on browser otherthan static files like pdf,excel,word these files will be downloaded .
'use strict';
const Path = require('path');
const Hapi = require('hapi');
var fs = require('fs');
const server = new Hapi.Server();
server.connection({
port: 3000,
host: 'localhost'
});
server.register(require('inert'), (err) => {
if (err) {
throw err;
}
server.route({
method: 'GET',
path: '/testdoc.docx',
handler: function(request, reply) {
var stream = fs.createReadStream('./testdoc.docx');
stream.on('data', function(data) {
console.log(data);
console.log('loaded part of the file');
//reply(null,data);
reply(data);
});
stream.on('end', function() {
console.log('all parts is loaded');
});
}
});
server.start((err) => {
if (err) {
throw err;
}
console.log('Server running at:', server.info.uri);
});
});
run the server node server.js and in browser run as http://localhost:3000/testdoc.docx. Hope this helps.