搭建nginx代理支持前端頁面跨域調用接口


前端同學因開發需要,本地搭建的服務需要調用其它域名的接口,在幫助正確配置后,已能正常使用。

這里寫一篇博客,記錄一下。

 

前端頁面地址為127.0.0.1:9813/a.html

接口地址http://test.cas.com/news/auth

 

讓前端在他自己電腦安裝好nginx后,在nginx.conf文件加入下面配置:

server{

       #任意一不在使用中的端口都行

  listen 3389;

  server_name localhost;

       #/表示所有請求www.l.com都會進入如下處理

   location / {

        #所有請求localhost:3389都會被轉發給test.cas.com域名下

    proxy_pass http://test.cas.com/;

    #以下配置是允許代理服務允許跨域

    add_header Access-Control-Allow-Origin *;

    add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";

    add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";

}

 

hosts文件新增綁定:  127.0.0.1 localhost

 

前端頁面代碼示例:

<html>
<body>

<h2>Index</h2>
<div id="show"></div>
<script src="https://common.cnblogs.com/scripts/jquery-2.2.0.min.js"></script>
<script type="text/javascript">
  $(function () {

    //代理服務會自動把參數轉發給test.cas.com域名下
    $.get("http://localhost:3389/news/auth?callback=jQuery31109208535942584586_1499060137214&newsTypeId=100", {}, function (result) {
      $("#show").html(result);
    })
  })
</script>
</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM