Jbonez87
Jbonez87

Reputation: 175

Uncaught SyntaxError: Unexpected token '<' express typescript

I'm using typescript to compile and run an express server that just serves an html file, but I keep getting this error in the response under the network tab in chrome for app.js: Uncaught SyntaxError: Unexpected token '<'

Here's my server code:

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}`)
})

Here's my folder structure: folder structure

Here's my command for compiling and running the code:

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

And here's my index.html file:

<!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>

Any idea what I've done wrong? I'm pretty sure the file path is correct, but I've tried ./app.js and removing the defer attribute from the <script> tag as well and I still get this error.

Upvotes: 0

Views: 979

Answers (1)

Đăng Khoa Đinh
Đăng Khoa Đinh

Reputation: 5411

This part isn't necessary, because you have already served static files in "dist" folder. You need to remove it.

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)
    }
  })
})

It will send index.html for all incoming requests, including the request to get app.js file. That's why you have Uncaught SyntaxError: Unexpected token '<', '<' is the first character in the HTML file which is unexpected for a script.

Upvotes: 2

Related Questions