最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - NodeJs: Unexpected token < error in javascript file - Stack Overflow

programmeradmin0浏览0评论

I am creating a single and a very simplest form of webpages where, i have created a js file for Nodejs: which looks like this:-

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

http.createServer(function (req, res) {
  
   fs.readFile('treeDemoinJavaScript.html', function (err, html) {
     if (err) {
        throw err; 
     }
    res.writeHeader(200, {'Content-Type': 'text/html'});
    res.write(html);
    res.end();
});
}).listen(8090);

I am creating a single and a very simplest form of webpages where, i have created a js file for Nodejs: which looks like this:-

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

http.createServer(function (req, res) {
  
   fs.readFile('treeDemoinJavaScript.html', function (err, html) {
     if (err) {
        throw err; 
     }
    res.writeHeader(200, {'Content-Type': 'text/html'});
    res.write(html);
    res.end();
});
}).listen(8090);

Then es the file treeDemoinJavaScript.html, which looks like this:-

<!DOCTYPE html>
<html>
<body>
<br>
<h2>Linked List in Javascript</h2>

<p>Click the button to sort the array in ascending order.</p>
INPUT
<input type="text"  id="inputList"> </input>
<button onclick="insertInTree()">Add in Tree</button>
</br>
<button onclick="insertIntoTree()" id="show">Show in Tree</button></br></br>
<button onclick="search()" id="search">Search in Tree</button>
<input type="text" id="searchtextbox" visibility="hidden" placeholder="type the input "> </input>
<button onclick="deletefunction()" id="delete">Delete from Tree</button>
<p id="demo">wele, the array is as follows: </p>
<p id="demo2">wele, the array is as follows: </p>
<script type="text/javascript" src="treeDemoInJavaScript.js">
</script>

</body>
</html>

Now what the problem is that even if i place a simple alert function in my treeDemoInJavaScript.js file that doesn't work and when i run by doing $terminal- node startNodeDemo.js Then in the chrome i get the following error, like this: Error shows :- Unexpected token < and i don't get that why does browser running the treeDemoInJavaScript.js file and showing error in it.

Share Improve this question edited Apr 29, 2021 at 22:12 Siddharth Choudhary asked Sep 25, 2017 at 4:39 Siddharth ChoudharySiddharth Choudhary 1,1291 gold badge15 silver badges21 bronze badges 3
  • 1 your server seems to be sending the HTML file for every request, and has no way of returning the JS file. – Claies Commented Sep 25, 2017 at 4:43
  • before a proper answer can be provided, it's important to know: Are you trying to do this without node plugins on purpose or would an example with plugins designed to deal with this situation be appropriate? In other words, is there some reason you are using fs, and not something like express? – Claies Commented Sep 25, 2017 at 5:01
  • A node.js server serves up NO files by default. So, your node.js server is configured to send treeDemoinJavaScript.html no matter what is requested of it. So, the browser requests treeDemoinJavaScript.html and the server sends that. Then the browser parses that HTML file and finds a reference to treeDemoinJavaScript.js so it request that from the web server, but your web server just sends it treeDemoinJavaScript.html which is why you get an error when the browser tries to run that as Javascript. You need to support a route in your web server for /treeDemoinJavaScript.js. – jfriend00 Commented Sep 25, 2017 at 5:14
Add a ment  | 

3 Answers 3

Reset to default 3

The problem with your code is that, for each request, it reads treeDemoinJavaScript.html, adds a header value of text/html, and writes the contents of the HTML file to the response.

If your browser needs treeDemoInJavaScript.js, it will request it from server, but the server will send an HTML file instead. The browser doesn't understand it, and hence throws the error.

First of all, I will remend to read this post. It will guide you on how to set a server up using NodeJS. The code you used defines the server interactions at very low-level. Using a dedicated framework for such cases, such as ExpressJS is highly remended.

Coming to the solution of your problem, this simple gist will help you enable your code to serve JS files.

First:

In your server side:

res.writeHeader(200, {'Content-Type': 'text/html'});

This is a typo mistake, instead of res.writeHeader, you should have used res.writeHead, as:

res.writeHead(200, { 'Content-Type': 'text/html' });

Second:

You're responding all requests as the content of the file treeDemoinJavaScript.html. When the page loads, this line will make another request to server:

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

Because of your mistake, it defaults response the file treeDemoInJavaScript.js with treeDemoInJavaScript.html's content, start with <!DOCTYPE html>, it's not valid syntax for javascript, so the error es. To solve, refer @31piy's answer.

Well I solved my issue, after putting a wastage of a day. I did it by two ways:

  1. By using Express.js as was suggested by @31piy by this blog, starting with express.js, I created and installed Express.js by npm install express --save mand and had got a package.json file. Now the story starts with creating the directory structure as was taught. But here es the mistake in this blog being done is, they have not guided you about the static files in express.js which was essential, because I added my javascript file everywhere but it was not reading it.

So what I needed to do was create a public folder parallel to views folder and then place my javascript file in it. And then using the line app.use(express.static('public')) to let Express know that some static files need to be include. And thus then directly using javascript.js in it

<!DOCTYPE html>
<br>
<h2>Linked List in Javascript</h2>

<p>Click the button to sort the array in ascending order.</p>
INPUT
<input type="text"  id="inputList"> </input>
<button onclick="insertInTree()">Add in Tree</button>
</br>
<button onclick="insertIntoTree()" id="show">Show in Tree</button></br></br>
<button onclick="search()" id="search">Search in Tree</button>
<input type="text" id="searchtextbox" visibility="hidden" placeholder="type the input "> </input>
<button onclick="deletefunction()" id="delete">Delete from Tree</button>
<p id="demo">wele, the array is as follows: </p>
<p id="demo2">wele, the array is as follows: </p>
<script type="text/javascript" src="javascript.js">
</script>

 and this is my index.js

const path = require('path')
const express = require('express')
const exphbs = require('express-handlebars')

const app = express()
app.use(express.static('public'))
//app.use("/styles", express.static(__dirname + '/js'));
app.engine('.hbs', exphbs({
  defaultLayout: 'main',
  extname: '.hbs',
  layoutsDir: path.join(__dirname, 'views/layouts')
}))
app.set('view engine', '.hbs')
app.set('views', path.join(__dirname, 'views'))

app.get('/', (request, response) => {
  response.render('home',{
    name: 'John'
  })
})
app.listen(8000)

  1. And now the Second way which is without using any Express.js

    well what my code here troubling with is this is rendering the js file and sending the html file which browser doesnot understand, as been pointed by other mentators. So what i did is used the switch case (as suggested by my friend) and changed the content-type of response which looks like this

var http = require("http"),
//url = require("url"),
path = require("path"),
fs = require("fs"),
mime = require("mime");


http.createServer(function (request, response) {
  console.log('request starting...');
  var filePath = '.' + request.url;
  if (filePath == './')
      filePath = './treeDemoinJavaScript.html';
      var extname = path.extname(filePath);
      var contentType = 'text/html';
      switch (extname) {
          case '.js':
              contentType = 'text/javascript';
              break;
          case '.css':
              contentType = 'text/css';
              break;
          case '.json':
              contentType = 'application/json';
              break;
          case '.png':
              contentType = 'image/png';
              break;
          case '.jpg':
              contentType = 'image/jpg';
              break;
          case '.wav':
              contentType = 'audio/wav';
              break;
      }

  fs.readFile(filePath, function(error, content) {
    if (error) {
      if(error.code == 'ENOENT'){
          response.writeHead(500);
          response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
          response.end();
      }
      else {
          response.writeHead(500);
          response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
          response.end();
      }
  }
  else {
      response.writeHead(200, { 'Content-Type': contentType });
      response.end(content, 'utf-8');
  }
  
  });

}).listen(8090);

and hence it worked. If it doesn't works in your case,then do focus on the paths which you might have given wrong or try to create new directory and do it neatly by including minimal files which you require

发布评论

评论列表(0)

  1. 暂无评论