首页 > 代码库 > 跨域访问接口上传图片出现options请求问题解决方法

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

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请求问题解决方法