0

I create simple nodeJs server this is my server.js file:

var http = require('http');
var fs = require('fs');
var path = require('path');

var server = http.createServer(function(req, resp){
  // Print the name of the file for which request is made.

  console.log("Request for demo file received.");
  fs.readFile("www/index.html",function(error, data){


    var filePath = '.' + req.url;

    var extname = path.extname(filePath);
    var contentType = 'text/html';
    if(extname ==  '.js'){
         contentType = 'text/javascript';
         console.log("extname is .js")
    }

     resp.writeHead(200, { 'Content-Type': contentType });

     resp.end(data, 'utf-8');
  });
});

server.listen(8081, '127.0.0.1');

this is my HTML file:

<!DOCTYPE html>
<html>
<head>
  <title>Professor Test DApp</title>
  <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
  <link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' rel='stylesheet' type='text/css'>
</head>
<body class="container">
  <h1>A Simple Test Professor DApp</h1>
  <div class="table-responsive">
  </div>
  <a href="#" onclick="apply()" class="btn btn-primary">Apply</a>
</body>
<script src="https://cdn.rawgit.com/ethereum/web3.js/develop/dist/web3.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>

<script  type="text/javascript" src="index112.js"></script>
</html>

and this is my js file:

function apply(){
  console.log("apply in js file called")
}

when I open it in the browser without a server it works fine but when I run it in server the js file cannot be detected.

SylvesterTheKid
  • 75
  • 1
  • 14
max
  • 5,963
  • 12
  • 49
  • 80
  • Is `index112.js` in the same directory as your html file? – Snel23 May 22 '19 at 06:20
  • yes, it is, those are in the same folder, as I said this work without nodejs server but when I want to run it in server it does not recognize the .js file. – max May 22 '19 at 06:42

2 Answers2

0

Please check your index112.js file path because while running on server there might be possiblity that server is not able to find the file try giving absolute or relative path of the file in src attribute this might help. Absolute or Relative Path Info

SylvesterTheKid
  • 75
  • 1
  • 14
  • yes, it is, those are in the same folder, as I said this work without nodejs server but when I want to run it in server it does not recognize the .js file – max May 22 '19 at 06:54
0

I think you need to serve static files. create public folder and move index112.js in public folder. use the express.static built-in middleware function as per the following.

app.use(express.static(path.join(__dirname, 'public')));
Paresh Barad
  • 1,544
  • 11
  • 18