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

启动Express服务器时遇SyntaxError无效令牌错误求助

Node.js Express启动报错:SyntaxError: Invalid or unexpected token(第1行)

运行node app.js启动Express服务器时,控制台抛出SyntaxError: Invalid or unexpected token错误,报错指向app.js文件第1行。以下是相关代码和完整报错信息:

app.js代码

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
    res.send('Hello World!')
})

app.listen(port, () => {
    console.log(`Example app listening on port`)
})

package.json代码

{
  "name": "weatherproject",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.1"
  }
}

完整报错信息

PS Z:\Programming\Web_Development\Web_Development_Udemy\NodeJs\API\WeatherProject\WeatherProject> node app.js
Z:\Programming\Web_Development\Web_Development_Udemy\NodeJs\API\WeatherProject\WeatherProject\app.js:1
��/

SyntaxError: Invalid or unexpected token
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1033:15)
at Module._compile (node:internal/modules/cjs/loader:1069:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47

解决方案

这个错误的核心原因是app.js文件带有UTF-8 BOM头,Node.js解析JS文件时会把BOM标记识别为无效字符,从而触发语法错误。解决方法如下:

  • 编辑器修改编码:用VS Code等编辑器打开app.js,点击右下角的编码标识(如显示"UTF-8 with BOM"),选择"通过编码保存",再选"UTF-8"即可移除BOM头。
  • 重新创建文件:新建空白app.js文件,手动复制粘贴代码内容(避免直接复制带BOM的原文件),保存后重新运行。
  • 命令行移除BOM:在Windows PowerShell中执行以下命令,直接移除文件的BOM头:
    Get-Content app.js | Out-File -Encoding UTF8 app.js
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 20:24:23