20191204-使用nginx解决ajax测试调用接口跨域问题

问题描述

之前要测试一个http的接口,在postman中测试成功,但使用ajax调用却跨域。于是通过使用ngin反向代理的方式来解决ajax调用跨域问题

测试页面的内容

<html>
<head>
<script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("#b01").click(function(){
     $.ajax({
      type : "POST",
      url : "http://xxx.xxx.xx.xx:8770/kfeinvoice/finance/invoiceViewByFinance",
      data : '{"originalOrderNo": "123456","dataSource": "01","queryType": "01","invoiceCode": "",   "invoiceNo": ""}',
      contentType : "application/json",
      dataType : "json",
      complete:function(msg) {
        console.log(msg)

        $("#myDiv").html(JSON.stringify(msg.responseJSON))
        $("#myDiv").append("<p>"+msg.responseText+"</p>")
      }
    });
  });
});
</script>
</head>
<body>

<div id="myDiv"><h2>通过 AJAX 改变文本</h2></div>
<button id="b01" type="button">改变内容</button>

</body>
</html>

nginx中的vhost,xx.conf的配置

server {
    listen 8770;
    server_name serv.com;
    index index.html;

    location ^~ /v/ {
        alias D:/xxx/;
        try_files $uri $uri/ /index.html;
    }

    location / {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://abc.xxx.com;
    }

    access_log  D:/data0/logs/www.access.log main;
}

nginx启动后,访问[http://localhost:8770/v/index.html]测试,返回结果正常。

原文地址:https://www.cnblogs.com/GYoungBean/p/11982603.html