axios solve cross-domain problems

Before and after recently upgraded my own website to generate end of the separation project (vue + springBoot), the inevitable cross-domain problems encountered. We learned a lot of knowledge, just share it, but also to consolidate what they have learned under.

     Speaking cross-domain, must first understand the CORS (Cross origin resource sharing) shared resources across domains, it is a w3c standard is a technical specification browser provides a web service method different domains sandbox script came from in order to avoid the browser's same-origin policy, it is the advanced version than JSONP mode. JSONP only supports GET requests, rather CORS addition to the GET request method also supports other HTTP request. CORS cross-domain allows the browser to send the server, XMLHttpRequest to issue to overcome only homologous AJAX request. (Want to know why produce cross-domain problem, please understand same-origin policy browsers)

    CORS browser makes a request, you need to increase the number of request header information, the server will decide whether to agree to this request based on this information. Required header field as follows:

    (1)Access-Control-Allow-Origin

              This header field is required. It specifies allowed to enter the domain name of the source, ip + port number. If the value is '*', acceptance of any domain name request, this approach is not recommended, mainly because its not safe, but also because if the browser's request carries cookie information, errors can occur following figure:

 

    (2) Access-Control-Allow-Credentials

                This field is optional. It allows setting whether to send cookie, to true that the cookie contained in the request, false is the opposite, the default is false. If your project requires a cookie you have to set this field. CORS request the default HTTP Cookie and does not transmit the authentication information, so that on this basis also need to set the front end (in an example axios): axios.defaults.withCredentials = true

    (3)Access-Control-Max-Age

                This field is optional. CORS for configuring cache time, i.e. the validity of this request, in seconds.

    (4)Access-Control-Allow-Methods

              This field is optional. The method allows the setting request.

     (5)Access-Control-Allow-Headers

             This field is optional. The request header is provided to allow

      (...) other relevant information, please refer to

       Tip: These settings are provided at the rear of the interceptor.
 

     For axios, it is vue2 advocating the use of a lightweight version of ajax. It is based on the promise of HTTP library. It creates XMLHttpRequests from the browser. If axios do not know, you can look at this two blog: https: //www.kancloud.cn/yunye/axios/234845 and https://www.jianshu.com/p/7a9fbcbb1114

     Later learned that these problems it can solve cross-domain, detailed code is as follows:

    (1) vue.js

      

Axios from Import 'Axios'
Import from Store '../store'
Import getToken to {} from '@ / utils / the auth'
Import the Message {,} from the MessageBox 'UI-Element'
// cookies each request carries information
axios.defaults = to true .withCredentials
// Create instance axios
const = axios.create-Service ({
the baseURL: process.env.BASE_API, // API of the base_url
timeout: 15000 // request time
})
// request interceptor
service.interceptors.request .use (config => {
the console.log (store.getters.token)
IF (store.getters.token) {
the console.log (getToken to ())
config.headers [ 'X--the Token'] = getToken to () // so that each token request carries a custom edit their own actual situation
var = getToken to token ()
Object.assign (config.headers, { 'token':token })
}
config return
}, error => {
// the Do something Request error with
the console.log (error) // for Debug
Promise.reject (error)
})
// respone interceptor
service.interceptors.response.use (
Response => {
/ **
* 20,000 are non-parabolic error code may be incorporated to modify their business
* /
the console.log (response.data)
const = RES response.data
IF {(res.code 20,000 ==!)
the Message ({
Message: RES .message,
of the type: 'error',
DURATION: 5 * 1000
})

// 50008: illegal token; 50012: other clients logged; 50014: token expired;
IF (res.code 50008 || === RES 50012 || === === res.code .code 50014) {
MessageBox.confirm ( 'you have been logged out, you can cancel to stay on this page, or log in again', 'OK sign out', {
confirmButtonText: 're-login',
cancelButtonText: 'cancel',
type: 'warning'
.}) the then (() => {
store.dispatch ( 'FedLogOut') the then (() => {.
location.reload () / / In order to re-instantiated objects vue-router avoid bugs
})
})
}
return null
} the else {
return response.data
}
},
error => {
IF (Error.message === 'the Network error' && error.config.url .endsWith ( '/ License')) {
the Message ({
Message: 'Unable to connect to the local agent, confirm that the agent is operating properly!',
type: 'error',
DURATION: 1000. 5 *
})
} the else {
Console .log (error + '' + error.config .url) // for debug
Message({
message: error.message + ' ' + error.config.url,
type: 'error',
duration: 5 * 1000
})
}
return Promise.reject(error)
}
)
export default service
 (2)springBoot

  

package xin.toheart.door.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@WebFilter(urlPatterns = { "/*" }, filterName = "loginAuthFilter")
public class LoginAuthFilter implements Filter {
private static Logger logger = LoggerFactory.getLogger(LoginAuthFilter.class);


@Override
public void destroy() {

}

@Override
void the doFilter public (the ServletRequest Request, the ServletResponse Response,
the FilterChain catena alberghiera) throws IOException, {ServletException
the HttpServletRequest REQ = (the HttpServletRequest) Request;
the HttpServletResponse REP = (the HttpServletResponse) Response;
// arrangement allows a plurality of the requested domain name
String [] allowDomains = { "http : //www.toheart.xin "," http://192.168.10.213:8080 "," HTTP: // localhost: 8080 "};
the Set allowOrigins = new new HashSet (Arrays.asList (allowDomains));
String originHeads = req.getHeader ( "Origin");
IF (allowOrigins.contains (originHeads)) {
// settings allow cross-domain configuration
// here to fill you allow cross-domain host ip (can be dynamically configured to allow specific domain name when formally launched and the IP)
rep.setHeader ( "Access-Control-the allow-Origin", originHeads);
}


// set the server allows the browser sends the request carries cookie
rep.setHeader("Access-Control-Allow-Credentials","true");
// 允许的访问方法
rep.setHeader("Access-Control-Allow-Methods","POST, GET, PUT, OPTIONS, DELETE, PATCH");
// Access-Control-Max-Age 用于 CORS 相关配置的缓存
rep.setHeader("Access-Control-Max-Age", "3600");
rep.setHeader("Access-Control-Allow-Headers","token,Origin, X-Requested-With, Content-Type, Accept,mid,X-Token");
response.setCharacterEncoding("UTF-8");
// response.setContentType("application/json; charset=utf-8");
chain.doFilter(request, response);
}

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

}


}

Guess you like

Origin www.cnblogs.com/zhangycun/p/10944071.html