jquery ajax error 403 is because the domain names of the front end and the server are different, which triggers the anti-hotlink mechanism. The solution is: 1. Open the corresponding code file; 2. Pass "public CorsFilter corsFilter() {... }" method to set the allowed domains.
The operating environment of this tutorial: Windows 7 system, jquery version 3.2.1, Dell G3 computer.
What should I do if jquery ajax reports error 403?
Ajax calls the server interface and reports a 403 error. Solution
Found the problem
Remotely calling the server interface in the front-end page reports a 403 error. If you access it directly in the browser, no error will be reported.
Ajax call result:
Browser call result:
Report 403 Reason
After analysis, it was found that the anti-leeching mechanism was triggered because the domain names of the front-end and the server were different.
Anti-hotlinking mechanism
The anti-hotlinking mechanism is implemented based on the referer of the http request header. The referrer is equivalent to the id of the browser page address. The browser initiates a request to the server. When making a request, the referer will be carried. The server uses the referer to determine whether it is its own domain name. If it is not, it will deny access. If it is, it will continue to access.
Solution
For your own project, you can solve the cross-domain problem by setting the allowed domains through code. The code is as follows:
@Configuration public class GlobalCorsConfig { @Bean public CorsFilter corsFilter() { //1.添加cors配置信息 CorsConfiguration config = new CorsConfiguration(); // 允许的域(根据需要进行设置),不要写*, config.addAllowedOrigin("http://localhost:6334"); //是否发送cookie信息 config.setAllowCredentials(true); //允许请求的方式 config.addAllowedMethod("OPTIONS"); config.addAllowedMethod("HEAD"); config.addAllowedMethod("GET"); config.addAllowedMethod("PUT"); config.addAllowedMethod("POST"); config.addAllowedMethod("DELETE"); config.addAllowedMethod("PATCH"); //允许的头信息 config.addAllowedHeader("*"); //有效时长 config.setMaxAge(3600L); //添加映射网络,拦截一切请求 UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource(); configurationSource.registerCorsConfiguration("/**", config); //返回新的CorsFilter return new CorsFilter(configurationSource); } }
Recommended learning: "jQuery Video Tutorial"
The above is the detailed content of What to do if jquery ajax reports error 403. For more information, please follow other related articles on the PHP Chinese website!