For cross-origin request separation between the frontend and backend

Source: Internet
Author: User
Tags send cookies nginx reverse proxy

For cross-origin request separation between the frontend and backend
1. Problem description:

When using react for development, the problem of separating post requests from the frontend and backend causes the request to fail.

2. What is cross-origin?

When a client initiates a network request to the server, the url contains three main information:Protocol, domain name (host), port). When the three parts are the same as the serverSame Source. However, as long as there is a differenceCross-origin call. It is limited by the same-source policy.

  Same-origin policyRestrict how documents or scripts loaded from one source interact with resources from another source. This is a key security mechanism used to isolate potential malicious files. The same-origin policy of the browser prevents client scripts (such as JavaScript) from making cross-site calls to services in different domains (usually XMLHttpRequest requests) to prevent cross-site scripting attacks ).

3. Multiple cross-origin solutions: 3.1. jsonp requests:

JSONP (json with padding filled json) utilizes a mechanism that uses src to reference static resources without cross-origin restrictions. It mainly initiates a callback on the client to process data reception and operations, and notifies the server of the callback function name, what the server needs to do is to place the data in the agreed callback function according to the javascript syntax. JQuery has been working with JSONP for a long time, making it easier to use.

  Simple implementation of jsonp:

1 // callback function 2 function jsonpCallback (data) {3 console. log ("jsonpCallback:" + data. name) 4} 5 $ ("# submit "). click (function () {6 var data = {7 name: $ ("# name "). val (), 8 id: $ ("# id "). val () 9}; 10 $. ajax ({11 url: 'http: // localhost: 3001/ajax/deal', 12 data: data, 13 dataType: 'jsonp', 14 cache: false, 15 timeout: // The jsonp field indicates the fields used by the server to obtain the callback function name 17 jsonp: 'callback', 18 // declare the name of the local callback function, by default, jquery randomly generates a function named 19 jsonpCallback: 'jsoncallback', 20 success: function (data) {21 console. log ("ajax success callback:" + data. name) 22}, 23 error: function (jqXHR, textStatus, errorThrown) {24 console. log (textStatus + ''+ errorThrown); 25} 26}); 27 });

 

3.2 cors

CORS (Cross-origin resource sharing) is attached to AJAX. It adds some HTTP Hearder fields to request and obtain resources with access permissions. CORS is transparent to developers becauseBrowserIt automatically performs different processing based on the request situation (simple and complex. The key to CORS is server configuration support. As CORS is a relatively "new" solution in W3C, the major Web parsing engines have not yet implemented strict specifications, so there may be some inconsistencies under different engines.

(1) Access-Control-Allow-Origin

This field is required. The value is eitherOriginThe field value is either*To accept requests from any domain name.

(2) Access-Control-Allow-Credentials

This field is optional. Its value is a Boolean value that indicates whether Cookie sending is allowed. By default, cookies are not included in CORS requests. SettrueThe Cookie can be included in the request and sent to the server together. This value can only be settrueIf the server does not want the browser to send cookies, delete this field. To send a Cookie,Access-Control-Allow-OriginYou cannot set it as an asterisk. You must specify a domain name that is consistent with the requested webpage. At the same time, cookies still follow the same-origin policy. Only cookies set by the server domain name are uploaded. Cookies for other domain names are not uploaded.document.cookieThe Cookie under the server domain name cannot be read.

(3) Access-Control-Expose-Headers

This field is optional. When a CORS request is sent,XMLHttpRequestObjectgetResponseHeader()The method can only get 6 basic fields:Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma. If you want to obtain other fields, you mustAccess-Control-Expose-Headers. The example above specifies,getResponseHeader('FooBar')Can ReturnFooBarField Value.

  Java Filter Implementation cors:

1 public class CorsFilter implements Filter {2 3 public void init (FilterConfig filterConfig) throws ServletException {4} 5 6 public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) 7 throws IOException, servletException {8 HttpServletResponse httpResponse = (HttpServletResponse) response; 9 httpResponse. setHeader ("Access-Control-Allow-Origin", "http: // localhost: 8081"); // sets the domain name that allows cross-Origin requests. cookie information must be sent, therefore, you must specify the specific domain name 10 httpResponse. setHeader ("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 11 httpResponse. setHeader ("Access-Control-Allow-Methods", "GET, PUT, DELETE, POST "); // If xhrFields: {withCredentials: true} is contained in the Cross-origin Request Method 12/*** ajax request }, 14 * When configuring cross-origin in the server background, you must add the Access-Control-Allow-Credentials request header to 15 */16 httpResponse. setHeader ("Access-Control-Allow-Credentials", "true"); // allows sending Cookie Information 17 httpResponse. setHeader ("Cache-Control", "no-cache, no-store, must-revalidate"); // supports HTTP 1.1.18 httpResponse. setHeader ("Pragma", "no-cache"); // Support HTTP 1.0. response. setHeader ("Expires", "0"); 19 chain. doFilter (request, response); 20} 21 22 public void destroy () {23 // TODO Auto-generated method stub24} 25}

 

Differences between jsonp and cors:

The advantages and disadvantages of the two are roughly complementary, which are described in the following section:

3.3. react uses webpack to configure proxy for cross-origin requests:

  The nginx reverse proxy can also be used as a proxy, but the request process is always in the pending status during configuration, so it takes a long time to respond. I don't know why, but it hasn't been solved yet, if you can see it, please kindly advise.

The nginx configuration is as follows:

 1 location ^~/ { 2              proxy_pass http://localhost:8080; 3              proxy_redirect default ; 4              proxy_set_header Host $host:80; 5              proxy_set_header X-Real-IP $remote_addr; 6              proxy_set_header REMOTE-HOST $remote_addr; 7              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 8               9             10         }

Because it failed, I switchedWebpackProxy Configuration:

First, configure webpack. config. js:

Module. exports = {//... Omit devServer: {port: '123', host: '123. 0.0.1 ', historyApiFallback: false, disableHostCheck: true, noInfo: false, stats: 'minimal', inline: true, // enable the server's module hot replacement (HMR) hot: true, // consistent with the "publicPath" value in the output above: publicPath: context, proxy: {'/sharemeeting/*': {target: "http: // localhost: 8080 ", changeOrigin: true, secure: false }}}//... Omitted };

 

 

In proxy, '/sharemeeting/*' is the path for filtering the request to be proxy. tartget is the address of the target server after proxy, including the protocol, domain name, and port number information. If the request is http: // localhost: 8081/sharemeeting/getTest. do. The proxy will be http: // localhost: 8080/sharemeeting/getTest. do.

  Fetch request

 

1 let url = "/sharemeeting/login/getTest. do "; 2 fetch (url, {3 method: 'post', 4 headers: {5 'accept': 'application/json', 6 'content-type ': 'application/json' 7}, 8 credentials: 'include ', 9 body: json. stringify ({}) 10 }). then (response) => response. json () // convert response to json11. then (responseData) ==>{// the preceding converted json12 if (responseData. status = false) {13 window. location. href = "#/"; 14} else {15 this. reset (responseData. data); 16} 17 }). catch (error) => {18 window. location. href = "#/"; 19 })

 

 

 

The request url must be defined as above. If so, the request will add the protocol and the domain name Port Number of the request,

 

 

============================================ Reference = ======================================

1. the respective advantages and disadvantages and application scenarios of JSONP and CORS in https://www.zhihu.com/question/41992168 JS cross-origin scheme?

2. Same source policy of http://www.ruanyifeng.com/blog/2016/04/same-origin-policy.html browser and Its Avoidance Method

3. http://www.ruanyifeng.com/blog/2016/04/cors.html CORS details

4. https://www.jianshu.com/p/3bdff821f859 Webpack dev server uses http-proxy to solve cross-domain Problems

 

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.