问题
Structure is:
src -main --resources ---vue.html ---example.js
vue.html is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>-->
<script src="./example.js"></script>
<script>
alert("I'm active");
</script>
this is working for the alert : I'm active
but 404 for
http://localhost:8080/example.js
but for, it gives error. SAme error.
By the way, the endpoind is that:
@GetMapping("/vue")
public ModelAndView getAllvue() {
return new ModelAndView("vue");
}
I go to http://localhost:8080/vue but I cant go to
http://localhost:8080/vue.js
It gives
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
But in intellj idea, when i right click html and say open in browser, it goes to
http://localhost:63343/myproject/templates/vue.html?_ijt=v7rpc3a98pdc66ml94fp8iikn
and my script works. This is **example.js**
alert("This script will load first");
So, what is blocking my js to work?
This is security config:
@Configuration
@EnableWebSecurity
//@EnableWebMvc
public class WebSecurity extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
String[] resources = new String[]{
"/",
"/home",
"/css/**",
"/icons/**",
"/images/**",
"/resources/**",
"/static/**",
"/js/**"
};
http.csrf().disable();
http.authorizeRequests()
.antMatchers(resources).permitAll()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/authenticateTheUser")
.defaultSuccessUrl("/dashboard")
.permitAll();
}
I also tried with those:
<script src="./example.js"></script>
<script src="../example.js"></script>
<script src="/example.js"></script>
<script src="templates/example.js"></script>
回答1:
Try the below code to load static files.
@Configuration
//@EnableWebMvc
public class MvcConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
String[] resources = new String[]{
"/",
"/home",
"/css/**",
"/icons/**",
"/images/**",
"/resources/**",
"/static/**",
"/js/**"
};
http.csrf().disable();
http.authorizeRequests()
.antMatchers(resources).permitAll()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/authenticateTheUser")
.defaultSuccessUrl("/dashboard")
.permitAll();
}
}
And call it in your html page like .
<script src="http://localhost:8080/myproject/resources/vau.js"></script>
Hope this will solve the issue.
来源:https://stackoverflow.com/questions/59855048/can-not-load-external-script-js-file-wtih-spring