You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中出现'Uncaught SyntaxError'错误的原因咨询

解决"Uncaught SyntaxError: Unexpected token '<'"错误

错误原因

你的Node.js服务器目前无论请求什么路径,都会返回index.html文件。当浏览器加载HTML后,会请求./main.js,但服务器依然返回HTML内容,浏览器把HTML代码当作JavaScript解析,就会在第一个字符<处触发语法错误。另外你还存在文件名不匹配的问题:JS文件实际叫index.js,但HTML里引用的是main.js。

修复方案

1. 修正HTML中的脚本引用

把HTML里的main.js改成index.js,确保文件名一致:

<!DOCTYPE html>
<html lang="de">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>NODE JS</title>
        <link rel="stylesheet" type="text/css" href="">
    </head>
    <body>
        <h1>HALLO NODE JS</h1>
        <script src="./index.js" defer></script>
    </body>
</html>

2. 修改Node.js服务器代码

让服务器根据不同请求路径返回对应文件,并设置正确的内容类型:

"use strict";

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

const server = http.createServer((request, response) => {
    console.log(request.url, request.method);
    
    let filePath;
    let contentType;

    // 根据请求路径匹配资源
    switch(request.url) {
        case '/':
        case '/index.html':
            filePath = './index.html';
            contentType = 'text/html';
            break;
        case '/index.js':
            filePath = './index.js';
            contentType = 'application/javascript';
            break;
        default:
            // 处理404
            response.writeHead(404, {'Content-Type': 'text/html'});
            response.end('<h1>404 资源不存在</h1>');
            return;
    }

    response.setHeader('Content-Type', contentType);
    fs.readFile(filePath, (error, data) => {
        if(error){
            console.log(error);
            response.writeHead(500, {'Content-Type': 'text/html'});
            response.end('<h1>服务器内部错误</h1>');
        } else{
            response.end(data);
        }
    });
});

server.listen(3000, 'localhost', ()=>{
    console.log("服务器已启动,监听端口3000");
})

关键修改说明

  • 根据request.url判断请求的资源类型,返回对应文件
  • 为HTML设置text/html类型,为JS设置application/javascript类型,确保浏览器正确解析
  • 增加了404和服务器错误的处理逻辑
  • 修正了原代码中respone的拼写错误(应为response)

内容的提问来源于stack exchange,提问作者Emirhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 11:12:50