Front-end AJAX requests a background cross-domain problem (resolution) of another host on the LAN

Source: Internet
Author: User

1. This method is not very appropriate, not safe enough, you need to write an interceptor

Web. XML configuration pointing to interceptors

<filter>        <filter-name>JsonFormat</filter-name>        <filter-class> com.qianmo.qmyj.common.jsonfilter</filter-class>    </filter>    <filter-mapping>        <filter-name>JsonFormat</filter-name>        <url-pattern>*.  do </url-pattern>    </filter-mapping>
 PackageCom.qianmo.qmyj.common;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;Importorg.springframework.stereotype.Component;Importjavax.servlet.*;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjava.io.IOException;/*** FileName: ${name} * Author:anpei * DATE:2017/5/16 * Description: * History:*/@Component Public classJsonfilterImplementsFilter {PrivateLogger Logger =Loggerfactory.getlogger (GetClass ());  Public voiddestroy () {} Public voidDoFilter (ServletRequest req, Servletresponse resp, filterchain chain)throwsservletexception, IOException {httpservletrequest request=(httpservletrequest) req; HttpServletResponse Response=(HttpServletResponse) resp; Logger.debug ("-------> Accept HTTP requests in the way:" + ((httpservletrequest) req). GetMethod () + "<------"); Request.setcharacterencoding ("UTF-8"); Response.setcharacterencoding ("UTF-8"); Response.setcontenttype ("Text/json"); Response.setheader ("Access-control-allow-origin", "*"); Response.setheader ("Access-control-allow-methods", "POST, GET, OPTIONS, DELETE, Put,head"); Response.setheader ("Access-control-max-age", "3600"); Response.setheader ("Access-control-allow-headers", "X-requested-with,content-type"); Response.setheader ("Access-control-allow-credentials", "true");//Response.AddHeader ("Access-control-allow-headers", "Origin, X-requested-with, Content-type, Accept");//String curorigin = Request.getheader ("Origin");//if (curorigin! = null) {//for (int i = 0; i < originproperties.length; i++) {//logger.debug ("--------> Allow cross-domain access from:" + originproperties[i] + "<---------");//if (Curorigin.equals (Originproperties[i])) {//Response.setheader ("Access-control-allow-origin", curorigin);//                }//            }//} else {//for unsolicited requests (such as entering requests directly in the browser's address bar), only allow our own machines to//Response.setheader ("Access-control-allow-origin", "http://127.0.0.1");//        }//Response.setheader ("Access-control-allow-methods", "POST, GET, OPTIONS, DELETE, Put,head");//request.setcharacterencoding ("UTF-8");//response.setcharacterencoding ("UTF-8");//Response.setcontenttype ("Text/json");Chain.dofilter (req, resp); }     Public voidInit (filterconfig config)throwsservletexception {}}

2. There is another way, I use in eclipse, there is no problem, but do not know why in idea always error, because of time, I did not delve into, chose the above solution, also posted below it.

----------------------Web. xml-------------------------------------------------<filter>        < Filter-name>cors</filter-name>        <filter-class> com.thetransactioncompany.cors.corsfilter</filter-class>    </filter>    < filter-mapping>        <filter-name>CORS</filter-name>        <url-pattern>*< /url-pattern>    </filter-mapping>
------------------------Util Tool Class (Corsconfig)---------------------------------------- Packagecom.commerce.utils;//allow Ajax cross-domain requestsImportOrg.springframework.context.annotation.Bean;Importorg.springframework.context.annotation.Configuration;Importorg.springframework.web.cors.CorsConfiguration;ImportOrg.springframework.web.cors.UrlBasedCorsConfigurationSource;ImportOrg.springframework.web.filter.CorsFilter; @Configuration Public classCorsconfig {Privatecorsconfiguration Buildconfig () {corsconfiguration corsconfiguration=Newcorsconfiguration (); Corsconfiguration.addallowedorigin ("*");//1Corsconfiguration.addallowedheader ("*");//2Corsconfiguration.addallowedmethod ("*");//3        returncorsconfiguration; } @Bean PublicCorsfilter Corsfilter () {Urlbasedcorsconfigurationsource source=NewUrlbasedcorsconfigurationsource (); Source.registercorsconfiguration ("/**", Buildconfig ());//4        return Newcorsfilter (source); }}

Introduction of two Jars

-------------------------pom.xml-------------------------------<dependency>        <groupId> com.github.pagehelper</groupid>        <artifactId>pagehelper</artifactId>        <version> 5.0.0</version>    </dependency>        <dependency>        <groupId> com.thetransactioncompany</groupid>        <artifactId>cors-filter</artifactId>        <version >2.5</version>    </dependency>
 Packagecom.commerce.utils;//allow Ajax cross-domain requestsImportOrg.springframework.context.annotation.Bean;Importorg.springframework.context.annotation.Configuration;Importorg.springframework.web.cors.CorsConfiguration;ImportOrg.springframework.web.cors.UrlBasedCorsConfigurationSource;ImportOrg.springframework.web.filter.CorsFilter; @Configuration Public classCorsconfig {Privatecorsconfiguration Buildconfig () {corsconfiguration corsconfiguration=Newcorsconfiguration (); Corsconfiguration.addallowedorigin ("*");//1Corsconfiguration.addallowedheader ("*");//2Corsconfiguration.addallowedmethod ("*");//3        returncorsconfiguration; } @Bean PublicCorsfilter Corsfilter () {Urlbasedcorsconfigurationsource source=NewUrlbasedcorsconfigurationsource (); Source.registercorsconfiguration ("/**", Buildconfig ());//4        return Newcorsfilter (source); }}

Front-end AJAX requests a background cross-domain problem (resolution) of another host on the LAN

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.