Nginx實現(xiàn)跨域

Nginx下載

  1. 概念
    1. 高性能web服務(wù)器
    2. 一般用作靜態(tài)服務(wù)器, 負(fù)載均衡
    3. 反向代理(跨域)


    nginx.png
  2. 下載

    1. win下載: 官網(wǎng)下載http://nginx.org/en/download.html
    2. mac下載: brew install nginx
  3. 配置文件

    1. win: C:\nginx\conf\nginx.conf
    2. mac: /usr/local/etc/nginx/nginx.conf
  4. Nginx命令

    1. 檢測配置文件格式是否正確: nginx -t
    2. 啟動nginx, 重啟nginx: nginx -s reload
    3. 停止: nginx -s stop
    4. Mac 打開配置文件: sudo vi /usr/local/etc/nginx/nginx.conf(也可直接編輯)

Nginx實現(xiàn)跨域

第一步 node服務(wù)端

    const http = require('http')
    const url = require('url')
    const server = http.createServer((req, res) => {
      const { method } = req
      const { pathname } = url.parse(req.url)
      res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' })
      if (pathname === '/list' && method === 'GET') {
        const data = JSON.stringify({ username: 'test', pwd: 123 })
        console.log(pathname);
        res.end(data)
      } else {
        res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' })
        res.end('404 not found')
      }
    })
    server.listen(3000, () => {
      console.log('listen port at 3000')
    })

第二步 web客戶端

    <!--通過http-server -p 3001 將客戶端啟動-->
    <body>
      測試頁面
      <script src="https://cdn.bootcss.com/axios/0.19.2/axios.js"></script>
      <script>
        axios.get('http://localhost:3002/list').then(data => {
          console.log(data)
        })
      </script>
    </body>

第三步 配置nginx

    # 設(shè)定http服務(wù)器, 之后請求都是http不是https
    http { 
        server {
            listen 3002;  # 偵聽3002端口
            server_name  localhost;    # 客戶端域名
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Credentials' 'true'; 
            add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS';
            # 靜態(tài)資源的地址, 可不配置也能實現(xiàn)跨域
            # location / {
            #     root   C:/Users/80021648/Desktop/js;  #定義服務(wù)器的默認(rèn)網(wǎng)站根目錄位置
            #     index  index.html index.htm app.html;  #定義首頁索引文件的名稱
            # }
            location /list{
                proxy_pass http://localhost:3000/list; # 代理轉(zhuǎn)發(fā)的服務(wù)端地址
            }
        }
    }

總結(jié)

    服務(wù)端: http://localhost:3000
    客戶端: http://localhost:3001
    nginx: http://localhost:3002
    
    客戶端請求nginx監(jiān)聽的端口,  nginx監(jiān)聽到端口請求, 然后代理轉(zhuǎn)發(fā)的服務(wù)端地址
    
    客戶端 -> 服務(wù)端
    axios.get('http://localhost:3000/list')
    變成 客戶端 -> nginx代理轉(zhuǎn)發(fā) -> 服務(wù)端
    axios.get('http://localhost:3002/list')
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容