jq ajax自定義請求頭
$.ajax({
type: "POST",
headers: {
Accept: "application/json; charset=utf-8",
Token: "xxx" //這個是自定義的請求頭
},
url: "XXX",
contentType: "application/json",
data: JSON.stringify(str),//將變數str轉為json數據,可忽略
dataType: "json",
success: function(result) {
if(result.code == 200) {//200:請求成功
consile.log("ok");
}
}
});
下面是過濾器的一個設置
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
res.setHeader("Access-Control-Allow-Headers", "Content-Type,Token");
//自定義跨域請求瀏覽器會先發送一個OPTIONS請求,伺服器要對其作出相應,瀏覽器才會正常發出請求
if (req.getMethod().equals("OPTIONS")) {
//設置響應狀態碼
res.setStatus(200);
return;
}
}
到這裡完成了配置
實例
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
HttpServletResponse res = (HttpServletResponse) response;
HttpServletRequest req = (HttpServletRequest) request;
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Credentials", "true");//是否允許發送Cookie
res.setHeader("Access-Control-Allow-Methods", "*");
res.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token");
//對客戶端自定義請求頭的應答
res.setHeader("Access-Control-Allow-Headers", "Content-Type,Token");
/**
* 針對自定義header問題
* 客戶端錯誤:Request header field Token is not allowed by Access-Control-Allow-Headers in preflight response.
* 原因:包含自定義header欄位的跨域請求,瀏覽器會先向伺服器發送OPTIONS請求,探測該伺服器是否允許自定義的跨域欄位。
* 如果允許,則繼續實際的POST/GET正常請求,否則,返回標題所示錯誤。
*/
if (req.getMethod().equals("OPTIONS")) {
//設值響應狀態碼
res.setStatus(200);
return;
}
chain.doFilter(request, response);
}
※unix環境高級編程讀後感
※作為程序員,有沒有讓你感到既無語又崩潰的程序命名?
TAG:程序員小新人學習 |