springboot ajax 提交403错误

xiaoxiao2021-02-28  69

由于开启了csrf 我用ajax post上传图片出现了403错误 $('#input-app-icon').change(function () { var formdata = new FormData(); var v_this = $(this); var fileObj = v_this.get(0).files; formdata.append("file", fileObj[0]); jQuery.ajax({ url: '/upload', type: 'post', data: formdata, cache: false, contentType: false, processData: false, dataType: "text", success: function (data) { }, error: function (data) { } }); });解决办法一、 配置中加入排除csrf的地址 private CsrfSecurityRequestMatcher csrfSecurityRequestMatcher() { CsrfSecurityRequestMatcher csrfSecurityRequestMatcher = new CsrfSecurityRequestMatcher(); List<String> list = new ArrayList<String>(); list.add("/druid"); list.add("/upload"); list.add("/ueditorcontrol"); csrfSecurityRequestMatcher.setExecludeUrls(list); return csrfSecurityRequestMatcher; } 解决办法二、 AJAX请求发送前执行函数。Ajax事件。

XMLHttpRequest对象和设置作为参数传递给回调函数

$(document).ajaxSend(function(evt,request,settings){})是全局事件,也就是说,

只要该页面定义了这个函数,那么,在每个ajax请求前都会执行该函数

head中添加 <meta name="_csrf" th:content="${_csrf.token}"/> <meta name="_csrf_header" th:content="${_csrf.headerName}"/>

js文件中添加

var token = $("meta[name='_csrf']").attr("content"); var header = $("meta[name='_csrf_header']").attr("content"); $(document).ajaxSend(function(e, xhr, options) { xhr.setRequestHeader(header, token); });
转载请注明原文地址: https://www.6miu.com/read-48174.html

最新回复(0)