简体   繁体   中英

HTTP/HTTPS Nodejs Serve Javascript with HTML

I have a very simple https Nodejs server that serves an index.html that includes a request for a Javascript file. I cannot seem to get the browser to recognize the Javascript file.

<html>
  <head>
    <script src="deviceMotion.js"></script>
  </head>
  <body>
  </body>
</html>

For this example, the contents of deviceMotion.js are immaterial. When I load the page and check Crhome debug tools, I receive a syntax error in the first line of the Javascript file, saying

Uncaught SyntaxError: Unexpected token '<'

I look at the "javascript" file's contents only to see that it is exactly the same as my index.html. This leads me to believe that there is an issue with the way my Node HTTPS server is serving the Javascript. Likely, it is just serving the html twice, even though my console logs show 3 separate requests being made, and only 2 when I remove the script tag from index.html. Obviously, it is trying to request the Javascript file, but there is something not right.

Here is the code for my server app.js

const http = require('http');
const fs = require('fs');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
    console.log("request received");
    console.log(req.headers.referer);
    fs.readFile('./src/index.html', function (error, data) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end(data);
    });
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

My files are structured such that I have app.js in the same directory as a folder called "src" and I have index.html and deviceMotion.js under src. How can I control what files I serve and when depending on incoming requests? How can I differentiate requests made in order to serve the right file? I have tried parsing req.baseUrl and req.path and both are undefined.

Your Node.js server always returns a HTML file and sets the content type to HTML, so when your website requests the JavaScript file, it returns a HTML file, causing the Uncaught SyntaxError: Unexpected token '<' error. To fix the error, don't set the content type and let the browser figure it out, and also modify the code to return the requested file.

I have written some possible code below. However, it will need to be modified to suit your file structure.

const server = http.createServer((req, res) => {
    console.log("request received");
    console.log(req.headers.referer);
    fs.readFile('./' + req.url, function (error, data) {
        res.end(data);
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM