【API设计风格—RESTful】:番外篇:跨域问题(四)
问题描述:
解决方法【1】设置response(此处只是了解,最终解决方案在下面)
@RequestMapping(value="/course/{id}",method=RequestMethod.GET)
public @ResponseBody Course GetCourse(@PathVariable("id") String courseid,HttpServletResponse response){
Course course=new Course();
course.setId(courseid);
//course.setCode(coursecode);
course.setCourseName("高等数学");
response.setHeader("Access-Control-Allow-Origin","*"); //允许哪些url可以跨域请求到本域
return course;
}
public class ResponseInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object obj) throws Exception {
response.setHeader("Access-Control-Allow-Origin","*"); //设置允许哪些url可以跨域请求到本域,*表示所有
return true;
}
public void postHandle(HttpServletRequest request,Object obj,ModelAndView mv) throws Exception {
}
public void afterCompletion(HttpServletRequest request,Exception ex)
throws Exception {
// TODO Auto-generated method stub
}
}
<!--拦截器配置 -->
<mvc:interceptors>
<!--自定义拦截器,用于允许跨域访问 -->
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.tgb.itoo.interceptor.ResponseInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
save: {method:'POST',isArray:false,headers: {'Content-Type': 'application/x-www-form-urlencoded'}},
2.设置代理服务器(最终解决方案)
整体说明
详细流程 设置代理路径
{
"name": "proxy-example","app_id": "","proxies": [ { "path": "/api","proxyUrl": "http://cors.api.com/api" } ] }
通过ionic serve启动你的服务器
设置 Angular Constant
angular.module('starter',['ionic','starter.controllers','starter.services'])
.constant('ApiEndpoint',{
url: 'http://localhost:8100/api'
}) // For the real endpoint,we'd use this // .constant('ApiEndpoint',{ // url: 'http://cors.api.com/api' // })
angular.module('starter.services',[])//NOTE: We are including the constant `ApiEndpoint` to be used here.
.factory('Api',function($http,ApiEndpoint) {
console.log('ApiEndpoint',ApiEndpoint)
var getApiData = function() {
return $http.get(ApiEndpoint.url + '/tasks')
.then(function(data) {
console.log('Got some data: ',data);
return data;
});
};
return {
getApiData: getApiData
};
})
通过 Gulp 自动转换地址
var replace = require('replace');
var replaceFiles = ['./www/js/app.js'];
gulp.task('add-proxy',function() {
return replace({
regex: "http://cors.api.com/api",replacement: "http://localhost:8100/api",paths: replaceFiles,recursive: false,silent: false,});
})
gulp.task('remove-proxy',function() {
return replace({
regex: "http://localhost:8100/api",replacement: "http://cors.api.com/api",});
})
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |