码迷,mamicode.com
首页 > Web开发 > 详细

跨域访问接口上传图片出现options请求问题解决方法

时间:2016-11-04 16:42:55      阅读:348      评论:0      收藏:0      [点我收藏+]

标签:exce   component   let   create   chain   服务   访问   spring   host   

1.首先因为服务器端会先发送一个option请求到后台  在后台返回一个post给页面 页面在处理post请求给接口 

2.先写一个过滤器, 我们自己定义一个过滤器

 

 

package com.adtime.dsp.web.controller;

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;

import org.springframework.stereotype.Component;

/**
* Created by kangb on 2016/5/10.
*/

public class myCORSFilter implements Filter {

@Override
public void init(FilterConfig filterConfig) throws ServletException {

}

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
String origin = (String) servletRequest.getRemoteHost()+":"+servletRequest.getRemotePort();
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
response.setHeader("Access-Control-Allow-Credentials","true");
filterChain.doFilter(servletRequest, servletResponse);
}

@Override
public void destroy() {

}
}

 

 

 

3.在web.xml里面配置过滤器

 

<!-- options 403 -->
<filter>
<filter-name>cors</filter-name>
<filter-class>com.adtime.dsp.web.controller.myCORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

 

 

4.过滤器会自动过滤options请求  然后就可以直接跨域访问接口了

 

跨域访问接口上传图片出现options请求问题解决方法

标签:exce   component   let   create   chain   服务   访问   spring   host   

原文地址:http://www.cnblogs.com/ckz0105/p/6030511.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!