In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to solve the cross-domain request problem of jsonp and CORS". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to solve the cross-domain request problem of jsonp and CORS.
JSONP
The principle of jsonp is very simple, using the idea that there is no cross-domain problem when the front end requests static resources.
But only get, only get, and only get are supported.
Note that since this method is called jsonp, the back-end data must use json data, not just a string or something, otherwise you will find the result inexplicable.
Front-end jQuery writing
$.ajax ({
Type: "get"
Url: baseUrl + "/ jsonp/get"
DataType: "jsonp"
Success: function (response) {
$("# response") .val (JSON.stringify (response))
}
});
DataType: "jsonp". Except for this, the other configurations are the same as normal requests.
Backend SpringMVC configuration
If you also use SpringMVC, then configure an Advice of jsonp, so that every Controller method we write does not need to consider whether the client is a jsonp request or not, and Spring will automatically handle it accordingly.
@ ControllerAdvice
Public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {
Public JsonpAdvice () {
/ / in this way, if there is a callback parameter in the request, Spring will know that this is a jsonp request.
Super ("callback")
}
}
The above writing requires that the SpringMVC version is not less than 3.2. if it is lower than 3.2, I can only say that it is time for you to upgrade.
Backend non-SpringMVC configuration
In the past, when I was just working, Struts2 was still popular all over the sky, but in a few years, SpringMVC basically dominated the domestic market.
To be lazy, post a pseudo code here and adjust the wrap method before our method returns to the front end:
Public Object wrap (HttpServletRequest request) {
String callback = request.getParameter ("callback")
If (StringUtils.isBlank (callback)) {
Return result
} else {
Return callback+ "(" + JSON.toJSONString (result) + ")"
}
}
CORS
Cross-Origin Resource Sharing
After all, jsonp only supports get requests, which certainly can't meet all our request needs, so we need to move out of CORS.
Domestic web developers are still quite miserable. Users refuse to upgrade their browsers, and the boss insists on developers being compatible.
CORS supports the following browsers. At present, browser problems are becoming less and less important. Even Taobao does not support IE7.
Chrome 3 +
Firefox 3.5 +
Opera 12 +
Safari 4 +
Internet Explorer 8 +
Front-end jQuery writing
Look directly at the code:
$.ajax ({
Type: "POST"
Url: baseUrl + "/ jsonp/post"
DataType: 'json'
CrossDomain: true
XhrFields: {
WithCredentials: true
}
Data: {
Name: "name_from_frontend"
}
Success: function (response) {
Json data returned by console.log (response) / /
$("# response") .val (JSON.stringify (response))
}
});
DataType: "json", this is json, not jsonp, not jsonp, not jsonp.
CrossDomain: true, which means to use cross-domain requests
XhrFields: {withCredentials: true}, so the configuration can bring cookie over, otherwise we won't even be able to maintain session, and a lot of people will be stuck here. Of course, if you don't have this requirement, you don't need to configure it.
Backend SpringMVC configuration
For most web projects, there is usually a mvc-related configuration class, which inherits from WebMvcConfigurerAdapter. If you also use SpringMVC 4.2 or later, you can simply add this method as follows:
@ Configuration
Public class WebConfig extends WebMvcConfigurerAdapter {
@ Override
Public void addCorsMappings (CorsRegistry registry) {
Registry.addMapping ("/ * * / *") .allowedOrigins ("*")
}
}
If unfortunately the SpringMVC version of your project is less than 4.2, then you need to "curve save the nation":
Public class CrossDomainFilter extends OncePerRequestFilter {
@ Override
Protected void doFilterInternal (HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
Response.addHeader ("Access-Control-Allow-Origin", "*"); / / if prompted * no, please read on
Response.addHeader ("Access-Control-Allow-Credentials", "true")
Response.addHeader ("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
Response.addHeader ("Access-Control-Allow-Headers", "Content-Type")
FilterChain.doFilter (request, response)
}
}
Configure filter in web.xml:
CrossDomainFilter
Com.javadoop.filters.CrossDomainFilter
CrossDomainFilter
/ *
There are a lot of projects that use shiro, or you can configure shiro filters, so I won't cover it here.
Note that I'm talking about a very general configuration, which can be configured in such a general way for most projects. Readers should know how to match a configuration like "*" in this article.
If the reader finds that the browser prompt cannot use the'* 'symbol, the reader can get the referer (request.getHeader ("referer")) in the request header according to the request object in the filter above, and then dynamically set "Access-Control-Allow-Origin":
String referer = request.getHeader ("referer")
If (StringUtils.isNotBlank (referer)) {
URL url = new URL (referer)
String origin = url.getProtocol () + ": / /" + url.getHost ()
Response.addHeader ("Access-Control-Allow-Origin", origin)
} else {
Response.addHeader ("Access-Control-Allow-Origin", "*")
}
2018-04-28: today we finally know why we are sometimes prompted * not supported. It turns out that as long as withCredentials: true is written in the front end, then the browser will prompt this. One way is to use the dynamic construction of origin here. Another way is not to send cookie across domains. Let the front end put the information to be transmitted by cookie (such as sessionId/accessKey) in header or write it directly in the parameters of request.
Front-end non-jQuery writing
The days of jQuery are gone, so here's how to solve the cross-domain problem of post if you don't use jQuery. Most js libraries will provide the corresponding solution, we directly look for the appropriate documentation to see how to use it.
Let's give an introduction to native js:
Function createCORSRequest (method, url) {
Var xhr = new XMLHttpRequest ()
If ("withCredentials" in xhr) {
/ / if you have the attribute withCredentials, you can be sure it is a XMLHTTPRequest2 object. Look at the third parameter.
Xhr.open (method, url, true)
} else if (typeof XDomainRequest! = "undefined") {
/ / this object is used by IE to request cross-domain requests.
Xhr = new XDomainRequest ()
Xhr.open (method, url)
} else {
/ / if so, unfortunately, browsers do not support CORS
Xhr = null
}
Return xhr
}
Var xhr = createCORSRequest ('GET', url)
If (! xhr) {
Throw new Error ('CORS not supported')
}
Among them, "programmer-friendly" browsers such as Chrome,Firefox,Opera,Safari use XMLHTTPRequest2 objects. IE uses XDomainRequest.
Thank you for your reading. The above is the content of "how to solve the cross-domain request problem of jsonp and CORS". After the study of this article, I believe you have a deeper understanding of how to solve the cross-domain request problem of jsonp and CORS, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.