最近用springboot開發後臺接口,可是接口開發好之後,用js請求接口json數據,遇到了煩人的跨域問題,也是找了很久才找到解決方法。下面來說解下解決步驟。css
把下面代碼放到你的springboot項目中就能夠了html
package com.qcl;
import org.springframework.stereotype.Component;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
/**
* 處理跨域問題
* qcl:微信2501902696
*/
@Component
public class OriginFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res);
}
@Override
public void destroy() {
}
}
複製代碼
如咱們須要請求https://localhost:8443/pv/2048/list 獲取以下數據,https://localhost:8443/pv/2048/list是我部署在服務器上的,2020年到期,你也能夠訪問java
{
"code": 100,
"msg": "成功",
"data": 3
}
複製代碼
對應的js請求代碼以下jquery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js+springboot解決跨域請求</title>
</head>
<body>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
var baseUrl = "https://30paotui.com";
$(document).ready(function () {
$("button").click(function () {
$.ajax({
url: baseUrl + "/pv/2048/list", success: function (result) {
document.getElementById("p1").innerHTML = result;
var str = JSON.stringify(result); //將JSON對象轉化爲JSON字符
var obj = JSON.parse(str); //由JSON字符串轉換爲JSON對象
console.log(str);
console.log(obj);
console.log(obj.data);
console.log(result.msg);
console.log(result.code);
}
});
});
});
</script>
<p id="p1"></p>
<button>獲取其餘內容</button>
</body>
</html>
複製代碼
請求效果以下 ajax
有任何關於編程的問題均可以留言或者私信我,我看到後會及時解答spring
編程小石頭,碼農一枚,非著名全棧開發人員。分享本身的一些經驗,學習心得,但願後來人少走彎路,少填坑。編程