簡體   English   中英

javascript 錯誤 - “SyntaxError: Unexpected token '<' (anonymous function)”在第一行

[英]javascript error - “SyntaxError: Unexpected token '<' (anonymous function)” in the very first line

作為一個整體,我對 webdev 還是很陌生,這是我第一次嘗試使用 Node.js 設置本地服務器。 但問題是我在 test.js 第 1 行中收到“SyntaxError: Unexpected token '<' (anonymous function)”。我知道它實際上不在第 1 行,因為第 1 行沒有代碼。此外,我的javascript 文件,html 文件和我的服務器 js 文件都是非常基本的,我不知道他們怎么會 go 出錯。

這是我的 test.js 文件



console.log('*');

這是我的索引。html 文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Test</h1>
</body>
<script type="text/javascript" src = "test.js"></script>
</html>

這是我使用“node server.js”運行的服務器文件

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

const port = 3000;

const server = http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    fs.readFile('../index.html', function(error, data) {
        if(error) {
            res.writeHead(404);
            res.writeHead('Error: File Not Found');
        } else {
            res.write(data);
        }
        res.end();
    })
});

server.listen(port, function(error) {
    if(error) {
        console.log('something went wrong', error);
    } else {
        console.log('Server is listenting on port ' + port);
    }
});

據我了解,這是最基本的千篇一律的代碼,我可以用來測試我的本地服務器、html 文件和 test.js 文件是否都可以很好地協同工作,但顯然出了點問題。 When I click on the error in the console, it shows my index.html file but says it is my test.js file almost as if the html is being read in place of my javascript and the javascript error handling is being applied to it. 我已經檢查了幾次路徑,我 99.99% 確定它們是正確的。 我對此一無所知,如果你們中的任何人遇到過類似的事情,請告訴我。 謝謝!

【原因描述】
沒有處理不同的請求或設置 static 資源。
您服務器中的所有請求都會響應 index.html。

在此處輸入圖像描述

您可以在 createServer function 中添加控制台日志。 因此,您會發現當 req.url 是 test.js 時,您仍然會返回 ./index.html 給請求。

const server = http.createServer(function (req, res) {
    console.log(req.url)
    res.writeHead(200, { 'Content-Type': 'text/html' });
    fs.readFile('../index.html', function(error, data) {
        if(error) {
            res.writeHead(404);
            res.writeHead('Error: File Not Found');
        } else {
            res.write(data);
        }
        res.end();
    })
});

[改進]
確保在請求 url 包含.js(或其他)時,它將返回正確的響應。

const server = http.createServer(function (req, res) {
    // fs.readFile('../index.html', function(error, data) {
    fs.readFile(__dirname + req.url, function (err,data) {
        if(error) {

https://nodejs.org/en/knowledge/HTTP/servers/how-to-serve-static-files/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM