i new node.js , unable find way solve issue. have written server using node.js serve html webpage. problem wont display images in same folder. trying serve webpage images , css file. appreciated.
relevant code:
server:
var http = require('http'); var fs = require('fs'); const port = 8080; function handlerequest(request, response) { console.log(request.url); var bool = 0; var index = fs.readfilesync("index.html", { encoding: "utf-8" }); if(request.url == "/") { bool = 1; response.end(index); } else if(request.url == "/index" || request.url == "/index.html") { bool = 1; response.end(index); } else if(bool == 0) { response.statuscode = 404; response.end("not found"); } } var server = http.createserver(handlerequest); server.listen(port, function() { console.log("started server on http://localhost:%s", port) });
html:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>my personal webpage</title> <link rel="stylesheet" href="index-css.css"/> </head> <body> <h1>welcome!</h1> <p>my paragraph.</p> <img src="/family.jpg" alt="family" style="width:342px;height:513px;"> <img src="/another.jpeg" alt="another" style="width:500px;height:500px;"> </body> </html>
i recommend use app.use(express.static(__dirname + '/folder_name'))
in order expose folder serve static files client. here documents serving static files using express.
edit: here simple working example of serving index.html using express
var app = require('express')(); var http = require('http').server(app); app.get('/', function(req, res){ res.sendfile(__dirname + '/index.html'); }); http.listen(3000, function(){ console.log('listening on *:3000'); });
Comments
Post a Comment