nginx: 处理 options 请求 返回204

使用 nginx 处理 cors 跨域
更新于: 2024-06-08 14:32:49

写一个简单的 API

  • 端口在 3000
  • 测试脚本 curl localhost:3000/heart
版本代码
无 cors
var express = require('express');
var app = express();

app.get('/heart', function (req, res) {
  res.json({message: 'Love from the server!'});
});

app.listen(3000, function () {
  console.log('Express app listening at http://localhost:3000');
});

 

使用 express cors
var express = require('express');
var cors = require('cors');
var app = express();

app.use(cors());  // 使用 CORS 中间件,表明允许所有源的请求

app.get('/heart', function (req, res) {
  res.json({message: 'Love from the server!'});
});

app.listen(3000, function () {
  console.log('Express app listening at http://localhost:3000');
});
无 cors + nginx 配置实现跨域

nginx 配置如下,下面的配置还不完整,无法实现 CORS

server {
  listen 80;
  server_name localhost;

  location /api/ {
     proxy_pass http://192.168.1.104:3000/; # 末尾添加斜线

     # location 删除前缀 /api
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     proxy_set_header X-Real-IP $remote_addr;
     proxy_set_header Host $http_host;

    # split /api/ to / and heart in $1, then append /$1 after proxy_pass
     rewrite ^/api/(.*) /$1  break;
  }
}

测试脚本修改为如下

<script>
// api: http://localhost:3000/heart
//
fetch('http://localhost/api/heart')
    .then(response => response.json())
    .then(data => console.log(data));
</script>

测试网页

  • 端口在 localhost:3002
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>HTML</title>
  </head>
  <body>
    <button>Send Request</button>
    <script>
      // api: http://localhost:3000/heart
      //
      var btn = document.querySelector('button');
      btn.onclick = () => {
        // const url1 = `http://localhost:3000/heart?ts=${Date.now()}`;
        const url = `http://localhost/api/heart`;

        fetch(url, {
          method: 'GET',
          mode: 'cors',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          }
        })
          .then((response) => response.json())
          .then((data) => console.log(data));
      };
    </script>
  </body>
</html>