nginx解決跨域問題


什么是跨域

  使用JS獲取數據時,涉及到的兩個URL只要協議,域名,端口有任何一個不同,都當做是不同的域,相互訪問就會有跨域問題;

怎樣使用nginx解決跨域問題

  步驟一:創建兩個工程AProject,BProject

     

  步驟二:在A工程中創建servlet

package com.wn; import com.alibaba.fastjson.JSON; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/aServlet") public class AServlet extends HttpServlet { //resp.setContentType("text/html;charset=utf-8");
 @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); }

    //方法四:使用nginx解決跨域問題
 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = req.getParameter("username"); System.out.println("數據:"+username); //響應
        resp.getWriter().write("success"); } }

  步驟三:在B工程中創建jsp頁面

<%-- Created by IntelliJ IDEA. User: wn Date: 2020/2/6 Time: 10:04 To change this template use File | Settings | File Templates. --%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>跨域</title>
    <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
    <script>
        //使用nginx解決跨域問題
 $(function () { $("#button").click(function () { var username=$("#username").val(); $.ajax({ url:"http://www.123.com:81/a/aServlet?username="+username, type:"GET", success:function (result) { alert(result) }, error:function () { alert("error!!!") } }) }) }) </script>
</head>
<body>
  <input type="text" name="username" id="username"/><button id="button" type="button">提交</button>
</body>
</html>

  步驟四:配置nginx.conf文件

server { listen 81; server_name www.123.com; #charset koi8-r; #access_log logs/host.access.log main; location / { root html; index index.html index.htm; } #nginx解決跨域問題 location /a { proxy_pass http://www.aproject.com:8080/;
 index index.html index.htm; } location /b { proxy_pass http://www.bproject.com:8081/;
 index index.html index.htm; }
}

  步驟五:啟動,實現效果

    使用www.123.com:81/b/bindex.jsp訪問B項目中的頁面

    

    輸入123文本,點擊提交按鈕,頁面將會淡出彈出success提示框,這樣就代表數據成功請求和響應;

    

    完成之后,A項目控制台中會接收到公共頁面提交的數據,並且servlet也將數據成功響應給頁面;

    

 

 

 


免責聲明!

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



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