问题:浏览器的console:Access to XMLHttpRequest at 'http://localhost:8080/web1/api/getXXX' from origin 'http://127.0.0.1:8088' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
1、设置Header响应头
- response.setHeader(“Access-Control-Allow-Origin”, “*”);// *表示所有请求允许跨域
- response.setHeader(“Access-Control-Allow-Origin”, “http://www.domain1.com”);// 只允许domain1域名访问
一般是写在过滤器或者拦截器中
2、使用JSONP
缺点:不支持post请求,代码书写比较复杂
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type : "GET",
async : false,
url : "http://localhost:8080/web1/api/getXXX",
dataType : "jsonp",
jsonp : "jsonpCallback", //服务端用于接收callback调用的function名的参数
success : function(data) {
alert(data["errorCode"]);
},
error : function() {
alert('fail');
}
});
});
</script>
后端代码:jsonpCallback 为jsonp生成的参数
@RequestMapping(value = "/ajaxB", method = RequestMethod.GET)
public void ajaxB(HttpServletResponse response, String jsonpCallback) throws IOException {
JSONObject root = new JSONObject();
root.put("errorCode", "200");
root.put("errorMsg", "登陆成功");
response.setHeader("Content-type", "text/html;charset=UTF-8");
PrintWriter writer = response.getWriter();
//需要把jsonp生成的参数带回前台,jsonp才能解析
writer.print(jsonpCallback + "(" + root.toString() + ")");
writer.close();
}
3、Nginx搭建API接口网关
- 访问 www.baidu.com/a 走A 项目同 http://a.baidu.com:8080/
- 访问 www.baidu.com/b 走B 项目同 http://b.baidu.com:8081/
- 两个项目都在同一个域名下 www.baidu.com,不会存在跨域问题
server {
listen 80;
server_name www.baidu.com;
###A项目
location /a {
proxy_pass http://a.baidu.com:8080/;
index index.html index.htm;
}
###B项目
location /b {
proxy_pass http://b.baidu.com:8081/;
index index.html index.htm;
}
}
4、HttpClient 转发
/**
* @description: 使用httpClient对象执行get请求
* @param: uri 需要跨域请求的uri
* @author:wu
* @throws IOException
* @throws ClientProtocolException
* @createDate:2018年2月28日 下午2:19:00
*/
public static String doGet(String uri) throws ClientProtocolException, IOException{
if(StringUtils.isBlank(uri)){
uri="http://localhost:8080/web1/api/getXXX";
}
// 1、 创建 httpClient 对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 2、 创建 get 对象
HttpGet get =new HttpGet(uri);
// 3、 执行 get 请求
CloseableHttpResponse response = httpClient.execute(get);
// 4、 获取返回结果 HttpEntity 对象
HttpEntity entity = response.getEntity();
// 5、获取返回结果中的数据
String data = EntityUtils.toString(entity);
// 6、 关闭 response、 关闭 httpClient
response.close();
httpClient.close();
return data;
}
/**
* @description:使用httpClient对象执行 post 请求
* @param: uri 需要跨域请求的uri , formDataMap 模拟表单需要提交数据 (name - value 形式)
* @author:wu
* @createDate:2018年2月28日 下午4:36:55
*/
public static String doPost(String uri,Map<String,Object> formDataMap) throws ClientProtocolException, IOException{
if(StringUtils.isBlank(uri)){
uri="http://localhost:8080/web1/api/getXXX";
}
// 1、创建httpClient 对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 2、 创建post 对象
HttpPost post =new HttpPost(uri);
// 3、 创建一个list形式数据,模拟提交表单。
List<NameValuePair> formDataList=new ArrayList<>();
// TODO: 这里可以遍历模拟表单传递过来的数据 formDataMap
/*Iterator<Entry<String, Object>> iterator = formDataMap.entrySet().iterator();
while(iterator.hasNext()){
Entry<String, Object> next = iterator.next();
String key = next.getKey();
String value = next.getValue().toString();
formDataList.add(new BasicNameValuePair(key, value));
}*/
formDataList.add(new BasicNameValuePair("ids", "110"));
formDataList.add(new BasicNameValuePair("name", "httpClient 请求数据"));
// 4、 把表单数据包装到entity 对象中 (StringEntity)
StringEntity formData = new UrlEncodedFormEntity(formDataList, "UTF-8");
post.setEntity(formData);
// 5、 执行post请求
CloseableHttpResponse response = httpClient.execute(post);
// 6、 获取响应数据
HttpEntity entity = response.getEntity();
// 7、 响应数据转换为字符串
String data = EntityUtils.toString(entity);
// 8、 关闭 httpClient对象、关闭 response
response.close();
httpClient.close();
return data;
}