nginx solve cross-domain problems

nginx solve cross-domain problems

 Read about 16 minutes

A. Produce cross-domain reasons

1. browser limitations
2. Cross-Domain
3.XHR (XMLHttpRequest) Request

II. Solutions

There are multiple solve cross-domain, where the main speaker with nginx solve cross-domain

1.JSONP
2.nginx agent
3. The browser prohibit cross-domain checks

III. Download and install nginx

nginx Download

  • Select a version to download, and then extract can be used
  • Enter nginx -v under nginx directory, if the version number appears, then the installation was successful
  • nginx

Four. Nginx reverse proxy to solve cross-domain (clients solve cross-domain)

1. We send a request using jquery ajax, node open back-office services

Front-end code:
the use of a transmission request of jQuery ajax api

    <button id="getOK">发送请求OK(客户端解决跨域问题)</button>
    <button id="getNO">发送请求NO(客户端解决跨域问题)</button>
    <script> $(document).ready(function () { $('#getOK').click(function () { $.ajax({ url:'http://localhost:3000/ok', success:function(res) { console.log("success",res) }, error:function(err) { console.log('fail',err) } }) }) $('#getNO').click(function () { $.ajax({ url:'http://localhost:3000/no', success:function(res) { console.log("success",res) }, error:function(err) { console.log('fail',err) } }) }) }) </script>

The rear end of the code:
the use of open framework of node express service, and according to the data format json url return,
provided the object of so many interfaces to the location behind matching configuration nginx

const express = require('express')
const cookieParser = require('cookie-parser') var app = express() var router = express.Router() router.get('/ok',function (req,res) { res.json({ code:200, msg:"isOK" }) }) router.get('/ok/son',function (req,res) { res.json({ code:200, msg:"isOKSon" }) }) router.get('/ok2',function (req,res) { res.json({ code:200, msg:"isOK2" }) }) router.get('/no',function (req,res) { res.json({ code:200, msg:"isNO" }) }) router.get('/no/son',function (req,res) { res.json({ code:200, msg:"isNOSON" }) }) router.get('/no/son2',function (req,res) { res.json({ code:200, msg:"isNOSON2" }) }) app.use(router) app.use(cookieParser) app.listen(3000,function () { console.log('listen in 3000') })

Then open the service node
Open node service
under test interface can now
Test Interface
be seen, the success of open service node
may now try to open nginx does not send ajax request services directly what happens
(note: send ajax request needs to open a Web page as a server, not as a file)
Cross-domain issues
As shown in the 5500 port 3000 port has requested cross-domain problem, this time you can turn on and configure nginx service location to resolve

2. Configure nginx reverse proxy to solve cross-domain

Reverse proxy principle is talking about front-end and back-end address to the same address forwarding addresses under nginx, such as ports 5500 and 3000 port to the next port 3003, the specific configuration is as follows:

  • Open nginx conf directory under the directory nginx.conf
  • In order to facilitate future test, we will configure separated, inflicted multiple files
  • Add the final include ../ vhost / test.conf http object of nginx.conf; (note to the last semicolon)
  • This can be configured separately at test.conf

Location specific configuration rules are as follows:
location of configuration rules nginx

server
{
   listen 3003;
   server_name localhost;
   ##  = /表示精确匹配路径为/的url,真实访问为http://localhost:5500
   location = / {
       proxy_pass http://localhost:5500; } ## /no 表示以/no开头的url,包括/no1,no/son,或者no/son/grandson ## 真实访问为http://localhost:5500/no开头的url ## 若 proxy_pass最后为/ 如http://localhost:3000/;匹配/no/son,则真实匹配为http://localhost:3000/son location /no { proxy_pass http://localhost:3000; } ## /ok/表示精确匹配以ok开头的url,/ok2是匹配不到的,/ok/son则可以 location /ok/ { proxy_pass http://localhost:3000; } }

The above code is meant to localhost: 3003 forwarded to location: 5500, that is now accessing localhost: 3003 is actually accessible location: 5500, and the visit localhost: 3003 / no access is localhost: 3000, and begin with the no url

  • Now we can open nginx service, and the use of start nginx nginx in the directory service to open

Open nginx Service

  • Every configuration changes need to be performed nginx -s reload command to take effect

reload
Now change the front-end code, the port interface before the request for the transducer 3003, as follows:

$('#getOK').click(function () {
                $.ajax({
                    url:'http://localhost:3003/ok', success:function(res) { console.log("success",res) }, error:function(err) { console.log('fail',err) } }) })

In the browser access is not too location: 5500, but localhost: 3003, and once again sends a request would not have cross-domain problem, because they are the same domain, this is nginx reverse proxy
success

V. backend configuration nginx solve cross-domain (the server to solve cross-domain)

1. still ajax + node

This is the front-end code

$(document).ready(function () {
            $('#get').click(function () { $.ajax({ url:'http://localhost:3002/ok', // 带cookies的请求 xhrFields:{ withCredentials:true }, success:function(res) { console.log("success",res) }, error:function(err) { console.log('fail',err) } }) }) })

In front of the rear end code as
well as configuration nginx follows:


server
{
    listen 3002;
    server_name localhost;
    location /ok {
        proxy_pass http://localhost:3000;

        #   指定允许跨域的方法,*代表所有
        add_header Access-Control-Allow-Methods *;

        #   预检命令的缓存,如果不缓存每次会发送两次请求
        add_header Access-Control-Max-Age 3600;
        #   带cookie请求需要加上这个字段,并设置为true
        add_header Access-Control-Allow-Credentials true; # 表示允许这个域跨域调用(客户端发送请求的域名和端口) # $http_origin动态获取请求客户端请求的域 不用*的原因是带cookie的请求不支持*号 add_header Access-Control-Allow-Origin $http_origin; # 表示请求头的字段 动态获取 add_header Access-Control-Allow-Headers $http_access_control_request_headers; # OPTIONS预检命令,预检命令通过时才发送请求 # 检查请求的类型是不是预检命令 if ($request_method = OPTIONS){ return 200; } } }

Non-simple request preflight command, concrete can see Mu class network ajax cross domain fully explain
not actually non-simple request without cookie with just two fields to solve cross-domain
add_header Access-Control-Allow-Methods * ;
add_header Access-Control-the Allow-Origin $ http_origin;

  • Specific effects as shown below:
  • Cross-domain server

Then just change ajax request port interface, no need to modify the address of the front-end server

Guess you like

Origin www.cnblogs.com/lgj8/p/12159606.html