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

Node.js服务器运行时出现Uncaught SyntaxError: Unexpected token '<'错误的求助

解决Node.js服务器返回HTML代替JS文件的问题

嘿,我完全懂你踩的这个坑!问题出在你的服务器代码上——不管浏览器请求什么路径,它都一股脑返回index.html的内容。当浏览器加载完HTML后,会自动去请求weatherApp.js,结果服务器把HTML文件返给它了,浏览器试图把HTML当成JavaScript解析,自然就抛出Unexpected token '<'的错误。

问题根源

你的createServer回调函数里,没有根据请求的URL做任何区分:不管是访问根路径/,还是请求/weatherApp.js,服务器都执行fs.readFile('index.html'),把HTML内容返回给浏览器。

解决方案:根据请求路径返回对应文件

我们需要修改服务器代码,让它根据req.url判断要返回哪个文件,同时设置正确的Content-Type(告诉浏览器返回的是什么类型的文件)。

修改后的index.js代码如下:

const http = require('http')
const fs = require('fs')
const port = 3000
require('dotenv').config()
const api_key = process.env.API_KEY

const server = http.createServer(function(req, res){
    // 处理根路径或index.html的请求
    if (req.url === '/' || req.url === '/index.html') {
        res.writeHead(200, { 'Content-Type': 'text/html' })
        fs.readFile('index.html', function(error, data) {
            if (error) {
                res.writeHead(404)
                res.write('Error: File not found')
            } else {
                res.write(data)
            }
            res.end()
        })
    } 
    // 处理weatherApp.js的请求
    else if (req.url === '/weatherApp.js') {
        res.writeHead(200, { 'Content-Type': 'application/javascript' })
        fs.readFile('weatherApp.js', function(error, data) {
            if (error) {
                res.writeHead(404)
                res.write('Error: JS file not found')
            } else {
                res.write(data)
            }
            res.end()
        })
    } 
    // 处理其他不存在的路径
    else {
        res.writeHead(404)
        res.write('Error: Page not found')
        res.end()
    }
})

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

关键细节说明

  • 区分请求路径:通过判断req.url的值,决定返回HTML还是JS文件。
  • 设置正确的Content-Type:
    • HTML文件用text/html,告诉浏览器这是网页内容;
    • JS文件用application/javascript,让浏览器知道这是可执行的脚本。
  • 错误处理:针对文件不存在的情况返回404错误,方便调试。

后续优化建议

如果以后你的项目要添加CSS、图片等更多静态资源,这种手动判断路径的方式会变得繁琐。这时可以考虑使用Express框架,它的express.static中间件能自动处理所有静态资源的请求,不用再手动写每个路径的判断逻辑。不过对于当前的小项目,上面的原生解决方案已经足够解决问题啦。

内容的提问来源于stack exchange,提问作者Joo Young Han

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 12:57:40