An article will help you understand how to solve cross domain problems with nginx

Bobo roast duck 2020-11-13 04:56:59
article help understand solve cross


Nginx Cross domain implementation

First of all, we should make clear what is cross domain , Why do cross domain situations occur . Which cases are cross domain ?

Cross domain : Because of the browser's same origin policy , That is, the pages belonging to different fields cannot visit each other's page content
notes : The same-origin policy , It's just an agreement , Same as domain name , Same port

URL explain Whether to allow communication
http://www.a.com/a.js
http://www.a.com/b.js Under the same domain name allow
http://www.a.com/lab/a.js
http://www.a.com/script/b.js Different folders under the same domain name allow
http://www.a.com:8000/a.js
http://www.a.com/b.js The same domain name , Different ports Don't allow
http://www.a.com/a.js
https://www.a.com/b.js The same domain name , Different protocols Don't allow
http://www.a.com/a.js
http://70.32.92.74/b.js Domain names correspond to domain names ip Don't allow
http://www.a.com/a.js
http://script.a.com/b.js Primary domain is the same , Different subdomains Don't allow
http://www.a.com/a.js
http://a.com/b.js The same domain name , Different secondary domains ( ditto ) Don't allow (cookie Access is also not allowed in this case )
http://www.cnblogs.com/a.js
http://www.a.com/b.js Different domain name Don't allow

Cross domain scenario

For safety reasons ( such as csrf attack ), Browsers generally prohibit cross domain access , But because sometimes there's a need , Need to allow cross domain access to , At this time , We need to turn on cross domain access restrictions .
Start a web service , The port is 8081
 Insert picture description here
Then turn on one more web service / Front end services are OK . The port is 8082, And then again 8082 Service through ajax To visit 8081 Service for , This does not satisfy the homology strategy , There will be cross domain problems

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<h2>Hello World!</h2>
<script type="text/javascript">
function fun1(){

var request = new XMLHttpRequest();
request.open("GET","http://localhost:8081/user/query")
request.send();
request.onreadystatechange = function(){

if(request.status==200 && request.readyState == 4){

console.log(" The result of the response " + request.responseText)
}
}
}
</script>
</body>
<input type="button" value=" Cross-domain calls " onclick="fun1()">
</html>

 Insert picture description here

Solutions to cross domain problems

There are many ways to solve cross domain problems .

1、 Combination of anterior and posterior ends (JsonP)

although jsonp You can also implement cross-domain , But because jsonp I won't support it post request , Application scenarios are very limited , So it's not right here jsonp Introduction .

2、 Pure back end mode one (CORS The way )

CORS yes w3c Standard way , By means of web Server settings : Response head Access-Cntrol-Alow-Origin To specify which domains can access the data of this domain ,ie8&9(XDomainRequest),10+,chrom4,firefox3.5,safair4,opera12 Support this way .

Server agent , The same origin policy only exists on the browser side , Forwarding the request through the server can achieve the purpose of cross domain request , Inferiority : Increase server burden , And slow access .

 Insert picture description here

3. Pure back end mode 2 (Nginx Agency mode )【 Suggest this way 】

First configuration Nginx The reverse proxy mode of
 Insert picture description here

Proxy access is normal
 Insert picture description here

8082 Service access for Nginx, There's a cross domain problem

 Insert picture description here

Nginx Configure cross domain resolution

location / {

add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
if ($request_method = 'OPTIONS') {

return 204;
}
proxy_pass http://192.168.12.1:8081;
}

Solved cross domain problems
 Insert picture description here

Parameter description

Access-Control-Allow-Origin

Servers are not allowed to cross domain by default . to Nginx Server configuration Access-Control-Allow-Origin * after , Indicates that the server can accept all request sources (Origin), That is to accept all cross domain requests .

Access-Control-Allow-Headers

Is to prevent the following mistakes :

Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

This error indicates the current request Content-Type The value of is not supported . In fact, we initiated "application/json" The type request of . Here's a concept : Pre inspection request (preflight request), Please see the following " Pre inspection request " Introduction to .

Access-Control-Allow-Methods

Is to prevent the following mistakes :

Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

to OPTIONS add to 204 Return

It's to deal with sending POST When asked Nginx Still deny access error , send out " Pre inspection request " when , You need to use methods OPTIONS , So the server needs to allow this method .

Pre inspection request (preflight request)

Cross-domain resource sharing (CORS) There's a new set of standards HTTP Header field , Allow the server to declare which origin has access to which resources . in addition , Specification requirements , For those that may have side effects on server data HTTP Request method ( especially GET Outside of the HTTP request , Or something MIME Type of POST request ), Browsers must first use OPTIONS Method to initiate a pre check request (preflight request), So we can know whether the server allows the cross domain request . After the server confirms the permission , To launch the actual HTTP request . In the return of the pre check request , The server can also notify the client , Do you need to carry ID card ( Include Cookies and HTTP Certification related data ).
Actually Content-Type The type of field is application/json The request is to match some of the above MIME Type of POST request ,CORS Regulations ,Content-Type It doesn't belong to the following MIME Type of , It's all pre inspection requests
therefore application/json Request Will be before formal correspondence , Add a " preview " request , This time, " preview " The request comes with a header Access-Control-Request-Headers: Content-Type:

OPTIONS /api/test HTTP/1.1
Origin: http://foo.example
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type
... Omit some

When the server responds , If the returned header does not contain Access-Control-Allow-Headers: Content-Type It means not accepting non default Content-Type. The following errors have occurred :

Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

版权声明
本文为[Bobo roast duck]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple