阅读量:0
问题描述:前端VUE、后端JAVA,代码放在本地可以完美运行,放在服务器外网不能运行delete和put,get和post不能运行
经过摸索总结,在不改变原有RESTful的情况下,亲身实验,得到两种解决办法:
一:改前端配置和nginx(后台是经过nginx代理)
前端http配置:
1.put和delete请求改为post请求
2.put请求添加请求头:X-Http-Method-Override: PUT;
delete请求添加请求头:X-Http-Method-Override: DELETE;
nginx配置:
在server里面添加如下代码
server { ... set $method $request_method; if ($http_X_HTTP_Method_Override ~* 'PUT|DELETE') { set $method $http_X_HTTP_Method_Override; } proxy_method $method; ... }
重启nginx,完毕!
二:改前端配置和后端配置(后台不经过nginx,直接访问)
前端http配置:
1.put和delete请求改为post请求
2.put请求添加请求头:X-Http-Method-Override: PUT;
delete请求添加请求头:X-Http-Method-Override: DELETE;
后端http配置:
新建一个过滤器类 ChangeHttpMethodFilter
import org.springframework.core.annotation.Order; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Component; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import java.io.IOException; /** * 改变请求头的过滤器 * * @author xu * 2024/3/28 12:08 */ @Order(1)// 执行顺序最小 @Component public class ChangeHttpMethodFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; String method = httpServletRequest.getHeader("X-Http-Method-Override"); // 如果修改和删除需要改变 if(HttpMethod.DELETE.name().equals(method) || HttpMethod.PUT.name().equals(method)){ HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(httpServletRequest) { @Override public String getMethod() { return method.toUpperCase(); } }; filterChain.doFilter(requestWrapper, servletResponse); }else { filterChain.doFilter(servletRequest, servletResponse); } } }
重启,完毕!