Amine Tanabene
Amine Tanabene

Reputation: 31

html can't call file.js

i created my first server.js, index.html and test.js. when i run with node, index page can't call test.js

var http = require('http');
var fs = require('fs');
var server = http.createServer(function(req, res) {
    fs.readFile('./index.html', 'utf-8', function(error, content) {
        res.writeHead(200, {"Content-Type": "text/html"});
        res.end(content);
    });
});

server.listen(8080);

index.html

    <!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>PLAN</title>
        <script type="text/javascript" scr="test.js"></script>
    </head>
    <body>
        hello 
    </body>
</html>

test.js

"use strict";
alert("aa1");

Upvotes: 1

Views: 110

Answers (1)

zdk
zdk

Reputation: 1576

There are 2 problems from yours.

  1. Incorrect <script> tag attribute, change from scr to src in your index.html file

  2. Your server needs to serve javascript file, that is fs.readFile('./test.js'), so Change your server.js to following.

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

http.createServer(function (request, response) {
var filePath = '.' + request.url;
if (filePath == './') filePath = './index.html';

var extname     = path.extname(filePath);
var contentType = 'text/html'
if (extname == '.js') contentType = 'text/javascript';

fs.readFile(filePath, function(error, content) {
    response.writeHead(200, { 'Content-Type': contentType });
    response.end(content, 'utf-8');
});

}).listen(8080);
console.log('Server running at http://127.0.0.1:8080/');

I think this should work.

Upvotes: 1

Related Questions