【问题标题】:Uncaught SyntaxError: Unexpected token '<' express typescript未捕获的语法错误:意外的标记“<”表示打字稿
【发布时间】:2021-08-11 17:37:14
【问题描述】:

我正在使用 typescript 编译和运行只提供 html 文件的快速服务器,但我在 app.js 的 chrome 中的网络选项卡下的响应中不断收到此错误:Uncaught SyntaxError: Unexpected token '&lt;'

这是我的服务器代码:

import { config } from 'dotenv'
import path from 'path'
import express from 'express'

config()

const app = express()

app.use(express.static(path.resolve(__dirname, "dist")))

app.get("*", (req, res) => {
  res.sendFile(path.resolve(__dirname, "index.html"), (err) => {
    if (err) {
      res.status(404).send(err)
    } else {
      res.status(500).send(err)
    }
  })
})

const port = process.env.PORT
app.listen(port, () => {
  console.log(`Listening on port ${port}`)
})

这是我的文件夹结构:

这是我编译和运行代码的命令:

"scripts": {
    "compile": "rimraf ./dist/ && tsc",
    "copy": "copyfiles -u 1 ./public/index.html ./dist",
    "start": "npm run compile && npm run copy && node dist"
  },

这是我的 index.html 文件:

<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='utf-8'>
  <meta http-equiv='X-UA-Compatible' content='IE=edge'>
  <meta name='viewport' content='width=device-width, initial-scale=1'>
  <title>TypeScript</title>
</head>
  <body>
    <script type="text/javascript" src="/app.js" defer></script>
  </body>
</html>

知道我做错了什么吗?我很确定文件路径是正确的,但是我尝试了./app.js 并从&lt;script&gt; 标记中删除了defer 属性,但我仍然收到此错误。

【问题讨论】:

    标签: html node.js typescript express


    【解决方案1】:

    这部分不是必需的,因为您已经在“dist”文件夹中提供了静态文件。您需要删除它。

    app.get("*", (req, res) => {
      res.sendFile(path.resolve(__dirname, "index.html"), (err) => {
        if (err) {
          res.status(404).send(err)
        } else {
          res.status(500).send(err)
        }
      })
    })
    

    它将为 所有 传入请求发送 index.html,包括获取 app.js 文件的请求。这就是为什么你有Uncaught SyntaxError: Unexpected token '&lt;','

    【讨论】:

    • 当我删除它时会引发错误:Cannot GET /。你是说完全删除这条 GET 路由还是不使用 * 作为一个包罗万象?
    • 是的,我的意思是应该删除路由。我认为这条路线没有必要,因为你有app.use(express.static(path.resolve(__dirname, "dist")))。错误Cannot GET / 对我来说是意料之外的。将 "*" 更改为 "/" 怎么样?所以它不会拦截获取app.js文件的请求。
    • 只有/ 我在控制台GET http://localhost:3000/app.js net::ERR_ABORTED 404 (Not Found) 中收到此错误
    • 我确定这条线 app.use(express.static(path.resolve(__dirname, "dist"))) 没有做它应该做的事情,因为我们无法访问静态文件...你可以试试 app.use(express.static(path.resolve(__dirname))) 吗?
    • 所以文件加载正确:) 现在是app.js内部的问题。这些链接可能对您有所帮助 stackoverflow.com/questions/42497479/…, stackoverflow.com/questions/43042889/…
    猜你喜欢
    • 2018-12-20
    • 2017-01-16
    • 2020-08-09
    • 2020-08-02
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 1970-01-01
    • 2019-05-25
    相关资源
    最近更新 更多