I want to make a very simple web server like this for example.
const http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.write("Hello!");
res.end();
}).listen(8080);
I put this code in WebStorm and ran it. Then I put in the same directory index.html file.
<body>
<button id="btn">Click Me</button>
<script src=".2.1.js"></script>
<script src="requester.js"></script>
</body>
I also put requester.js file in the same folder.
$('#btn').on("click", function () {
$.get('/', function () {
console.log('Successful.');
});
});
Then I execute mand live-server in this folder where all files are. I don't know how to make the server to work on localhost. Thank you in advance.
I want to make a very simple web server like this for example.
const http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.write("Hello!");
res.end();
}).listen(8080);
I put this code in WebStorm and ran it. Then I put in the same directory index.html file.
<body>
<button id="btn">Click Me</button>
<script src="https://code.jquery./jquery-3.2.1.js"></script>
<script src="requester.js"></script>
</body>
I also put requester.js file in the same folder.
$('#btn').on("click", function () {
$.get('/', function () {
console.log('Successful.');
});
});
Then I execute mand live-server in this folder where all files are. I don't know how to make the server to work on localhost. Thank you in advance.
Share Improve this question asked Sep 10, 2017 at 13:23 Симеон СимеоновСимеон Симеонов 1713 silver badges14 bronze badges 3- You havent shown any effort to actually send the file to the user. Have a look at expressjs., especially their .static method... – Jonas Wilms Commented Sep 10, 2017 at 13:39
- I need to do this only with http module. Is it possible? – Симеон Симеонов Commented Sep 10, 2017 at 13:42
- Yes. Have a look at .sendFile, fs.readFile, Streams. – Jonas Wilms Commented Sep 10, 2017 at 13:43
1 Answer
Reset to default 5You want to send your index.html
file instead of the string "Hello":
const http = require('http');
const fs = require('fs');
const path = require('path');
http.createServer(function (req, res) {
//NOTE: This assumes your index.html file is in the
// . same location as your root application.
const filePath = path.join(__dirname, 'index.html');
const stat = fs.statSync(filePath);
res.writeHead(200, {
'Content-Type': 'text/html',
'Content-Length': stat.size
});
var stream = fs.createReadStream(filePath);
stream.pipe(res);
}).listen(8080);
Depending on the plexity of your server in the future, you may want to investigate express as an alternative to the built-in http module.