Home > Software engineering >  Uncaught SyntaxError: Unexpected token '<'
Uncaught SyntaxError: Unexpected token '<'

Time:10-30

New to coding and I'm using node.js, javascript, and html. When I run the server using "node index.js" on the terminal, it gives me an error "Uncaught SyntaxError: Unexpected token '<'(at weatherApp.js:1:1)" and weatherApp.js file displaying the error is the index.html...

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){
    //#200 represents good status code
    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()
    })
})

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

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="weatherApp.js" type="text/javascript"></script>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Weather App</title>
</head>
<body>
    <input type="text" placeholder="Search City">
    <button type="button" id="searchButton" onclick="test()">Search</button>
</body>
</html>

the weatherApp.js is just a simple function containing console.log.

I tried removing the and the error goes away but still want to be able to keep and attach .js files if possible.

CodePudding user response:

You need to check if the request URL was the JS file, and if so, send the JS file back:

const server = http.createServer(function(req, res){
    if (req.url.startsWith("/weatherApp.js")) {
        res.writeHead(200, { 'Content-Type': 'text/javascript' });
        return fs.readFile('weatherApp.js', function (error, data) {
            if (error) {
                res.writeHead(404);
                res.write('Error: File not found');
            } else {
                res.write(data);
            }
            res.end();
        });
    }
    
    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()
    })
})

Consider using a modern http server framework like fastify. As you can see, the boilerplate here is quite the mess and a library can help greatly with that.

  • Related