javascript - Running Node JS server on localhost -
i want make simple web server 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 code in webstorm , ran it. put in same directory index.html file.
<body> <button id="btn">click me</button> <script src="https://code.jquery.com/jquery-3.2.1.js"></script> <script src="requester.js"></script> </body>
i put requester.js file in same folder.
$('#btn').on("click", function () { $.get('/', function () { console.log('successful.'); }); });
then execute command live-server in folder files are. don't know how make server work on localhost. thank in advance.
you want send index.html
file instead of string "hello":
const http = require('http'); const fs = require('fs'); const path = require('path'); http.createserver(function (req, res) { //note: assumes index.html file in // . same location 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 complexity of server in future, may want investigate express alternative built-in http module.
Comments
Post a Comment