arash moeen
arash moeen

Reputation: 4693

Spring mvc loading JS with Uncaught SyntaxError: Unexpected token <

I'm using Spring boot. I have this structure for a simple test app:

enter image description here

What I do in my TestController is to get 2 path variables and load index.html:

@Controller
public class TestController {

    @RequestMapping("/{vara}/{varb}")
    public String index(@PathVariable(value="vara") String vara, @PathVariable(value="varb") String varb) {
        return"/index.html";
    }
}

and the index.html is empty, clean html page:

<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
TEST
</body>
</html>

so typing localhost:8080/abbas/mirza in my browser and everything looks ok and the html page loads easily. I have 2 js files, test.js and /js/testb.js which both have this line of code inside.

var s = {}; 

Now I add this

<script src="/test.js"></script>

and everything is still ok and I can view the test.js code, but when I add

<script src="/js/testb.js"></script>

the page throws an exception

Uncaught SyntaxError: Unexpected token <

and when I try to open the testb.js file it shows me this

enter image description here

if I move testb.js into the webapp itself, it will be loaded with no problem. I'm quite newbie using the Spring mvc and still confused with all the configuration regarding routings and accessing resources.

Any idea what I'm doing wrong?

Edit:(link to github) https://github.com/arashzz/test22

Upvotes: 0

Views: 2075

Answers (2)

Kyle Anderson
Kyle Anderson

Reputation: 7031

The @RequestMapping pattern you're using is so broad that the path to your JavaScript file testb.js matches it and thus the index page is served in lieu of your js file causing the syntax error to occur.

Controller:

@RequestMapping("/{vara}/{varb}")

JavaScript Path:

/js/testb.js

This matches that pattern where vara=js and varb=testb.js

Your other JavaScript file is located at /test.js and thus doesn't match the pattern and is served correctly.

Solution:

Adjust the @RequestMapping pattern to something more narrow such as:

@RequestMapping("/placeholder/{vara}/{varb}")

Upvotes: 3

Issam El-atif
Issam El-atif

Reputation: 2486

Try <script src="js/testb.js"></script> without /as index.html and js directory are in same directory level

Upvotes: 0

Related Questions