一,编写Filter过滤器
把下面代码放到你的springboot项目中就可以了
代码解读
复制代码
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() {
}
}
二,用js做下请求验证下
代码解读
复制代码
{
"code": 100,
"msg": "成功",
"data": 3
}
对应的js请求代码如下
代码解读
复制代码
<!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>
请求效果如下
作者:编程小石头
链接:https://juejin.cn/post/6844903857198202888
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。