2017-09-25 48 views
1

我創建一個單一的和在那裏,我已經創造了的NodeJS一個js文件的網頁非常簡單的形式:它看起來像這樣: -的NodeJS:意外標記<錯誤javascript文件

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);

然後是文件treeDemoinJavaScript.html,它看起來像這樣: -

<!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">welcome, the array is as follows: </p> 
 
<p id="demo2">welcome, the array is as follows: </p> 
 
<script type="text/javascript" src="treeDemoInJavaScript.js"> 
 
</script> 
 

 
</body> 
 
</html>

現在的問題是什麼,即使我在treeDemoInJavaScript.js文件放在一個簡單的報警功能不能正常工作,當我在做 $端 - 節點startNodeDemo.js 然後運行 鉻我碰到下面的錯誤,像這樣: enter image description here

錯誤顯示: - 意外令牌< 和我沒有得到爲什麼瀏覽器中運行treeDemoInJavaScript.js文件,並顯示它的錯誤。

+1

您的服務器似乎正在發送每個請求的HTML文件,並且無法返回JS文件。 – Claies

+0

在提供正確的答案之前,知道以下幾點非常重要:您是否試圖在沒有使用節點插件的情況下執行此操作,或者是否有插件旨在處理這種情況的示例是適當的?換句話說,你是否有某些原因使用'fs',而不是表達式? – Claies

+0

默認情況下,node.js服務器提供NO文件。所以,你的node.js服務器被配置爲發送'treeDemoinJavaScript.html',不管它是什麼請求。所以,瀏覽器請求'treeDemoinJavaScript.html',服務器發送它。然後瀏覽器解析該HTML文件並找到對'treeDemoinJavaScript.js'的引用,以便從Web服務器請求,但是您的Web服務器只是將它發送給'treeDemoinJavaScript。這就是爲什麼當瀏覽器嘗試以Javascript運行時出現錯誤的原因。您需要在您的Web服務器中爲'/ treeDemoinJavaScript.js'提供支持。 – jfriend00

回答

0

第一:

在您的服務器端:

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

這是一個錯字的錯誤,而不是res.writeHeader,你應該使用res.writeHead,如:

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

第二個:

您正在回覆所有請求作爲文件treeDemoinJavaScript.html的內容。頁面加載時,這條線將另一個請求服務器:

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

因爲你的錯誤,它默認響應文件treeDemoInJavaScript.jstreeDemoInJavaScript.html的內容,先從<!DOCTYPE html>,這還沒有爲JavaScript有效語法,所以錯誤來了。要解決,請參閱@ 31piy的答案。

+0

我不認爲這是正確的。如果查看屏幕截圖,正在查看的文件是'treeDemoInJavaScript.js',但該文件**的**內容是'treeDemoinJavaScript.html'。這顯然是因爲服務器只做一件事。檢索文件'treeDemoinJavaScript.html'併發送它,**對於每個請求**,無論哪個文件被請求。 – Claies

+0

@Claies因爲'Content-Type'設置不正確,所以響應是Javascript而不是HTML。 –

+0

不,不,不。因爲**瀏覽器請求了一個javascript文件,但服務器被硬編碼以發送HTML文件的所有內容。**如果你真的看了截圖,它會使HTML顯示得很好。 – Claies

2

您的代碼的問題是,對於每個請求,它讀取treeDemoinJavaScript.html,添加一個標頭值text/html,並將HTML文件的內容寫入響應。

如果您的瀏覽器需要treeDemoInJavaScript.js,它會從服務器請求它,但服務器將發送一個HTML文件。瀏覽器不理解它,並因此引發錯誤。首先,我會推薦閱讀this post。它將指導您如何使用NodeJS設置服務器。您使用的代碼定義了非常低級別的服務器交互。強烈建議對這種情況使用專用框架,例如ExpressJS

即將解決您的問題,this simple gist將幫助您啓用您的代碼來提供JS文件。

+0

但我想要做的是,使一個簡單的和最小的代碼,並且這意味着不使用Express框架,那麼我怎麼才能做到這一點通過在這個代碼只做一些小的改變。 –

+0

@SiddharthChoudhary - 製作一個簡單而且非常簡單的代碼_ - 這就是快遞所做的。否則,你必須有一個if塊來檢查JS文件的URL,並相應地返回響應。這就是要點。 – 31piy

+0

所以現在按照你的建議,我在我的app文件夾中安裝了express。現在我該如何處理我的起始文件,我的意思是位於index.js文件中的代碼,請問我知道嗎? @ 31piy –

0

好吧,我解決了我的問題後,浪費了一天。 我做到了通過兩種方式:

  1. 通過使用Express.js作爲建議由@ 31piy通過this blog, 開始express.js,我創建並NPM安裝Express.js 安裝快車 - 保存命令並獲得了package.json文件。 現在,故事從創建目錄結構開始,就像教導的一樣。 但是,在這篇博客中,他們的母親錯誤是,他們沒有引導你關於express.js中的靜態文件,這是必不可少的,因爲我在任何地方都添加了我的JavaScript文件,但它沒有讀取它。

所以我需要做的是創建一個公共文件夾並行視圖文件夾,然後將我的JavaScript文件放在其中。 然後使用該行 app.use(express.static('public')) 讓Express知道需要包含一些靜態文件。因而然後直接使用javascript.js在它

<!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">welcome, the array is as follows: </p> 
 
<p id="demo2">welcome, 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)

  • 和現在的方式二這是沒有使用任何Express.js

    以及我在這裏遇到的麻煩是這是渲染js文件併發送瀏覽器不理解的html文件,正如其他評論員指出的那樣。 所以我所做的是使用的開關情況下(我的朋友的建議),並改變了內容類型響應 的,看起來像這樣

  • 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);

    ,因此它工作。 如果它不適用於您的情況,那麼請專注於您可能給出錯誤的路徑或嘗試創建新目錄,並通過包含所需的最小文件來完成它