如果你的项目需要设置header 但是报跨域问题如何解决?

来源:互联网 发布:mysql大小写 字符串 编辑:程序博客网 时间:2024/06/01 22:55

1、报跨域问题很多时候是因为,修改 header 会导致,正常的POST请求,会变成 option +post 的两次请求。


2、服务端需要对于这样的请求进行处理。


3、第一步:让你的web.xml 为开放options方法。

<servlet>    <servlet-name>DispatcherServlet</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <init-param>        <param-name>contextConfigLocation</param-name>        <param-value>classpath:springmvc.xml</param-value>    </init-param>    <init-param>        <param-name>dispatchOptionsRequest</param-name>        <param-value>true</param-value>    </init-param>    <load-on-startup>1</load-on-startup></servlet>


4、让你的springmvc,只接受options 接口以及 你需要的那个方法。例如


@RequestMapping(value ="123" ,method = Request.POST)


@RequestMapping(value ="123" ,method = Request.OPTIONS)



5\、在你的OPTIONS中设置 你的请求头

httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type,userLon,userLat");httpServletResponse.setHeader("Access-Control-Allow-Methods","PUT,GET,POST,DELETE,OPTIONS");
记住,可允许的 header中,你要把你自己自定义的header写在上面哦







阅读全文
0 0