CORS无法在Nginx的Docker容器上工作

ruyhziif  于 2024-01-06  发布在  Nginx
关注(0)|答案(1)|浏览(338)

由于我是Node、Nest、Docker和Ngnix的新手,我在容器中应用CORS,但没有工作。
我的应用架构是:

  1. |-ngnix docker
  2. |-Frontend (React) - Docker container - //Published on localhost:80
  3. |-Backend (NestJS/GraphQL) - Docker Container - //Published on localhost:3000
  4. |-nodeJS - Docker Container - // //I am expecting published to localhost:3004 to receive CORS

字符串
我的Nginx配置是:

  1. server {
  2. listen 80;
  3. location /api {
  4. #rewrite ^/api$ /api/ permanent;
  5. #rewrite ^/api/(.*)$ /$1 break;
  6. proxy_http_version 1.1;
  7. proxy_set_header Host $host;
  8. proxy_set_header X-Real-IP $remote_addr;
  9. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  10. proxy_set_header Host $host;
  11. proxy_set_header Upgrade $http_upgrade;
  12. proxy_set_header Connection "upgrade";
  13. #add_header Access-Control-Allow-Origin *;
  14. #add_header Access-Control-Max-Age 3600;
  15. #add_header Access-Control-Expose-Headers Content-Length;
  16. #add_header Access-Control-Allow-Headers Range;
  17. proxy_pass_request_headers on;
  18. proxy_pass http://nestbackend:3000/;
  19. #this is NestJS I have already implemented app.enableCors();
  20. }
  21. location /api2 {
  22. proxy_pass http://api2:3004/;
  23. }
  24. location / {
  25. proxy_pass http://frontend:3003/;
  26. }
  27. }


我的NodeJS api 2是:

  1. const express = require("express");
  2. const app = express();
  3. let cors = require("cors");
  4. require("dotenv").config();
  5. app.use(cors());
  6. app.post("/graphql", async (req, res) =>{
  7. console.log("Testing CORS!!!!!!!!");
  8. console.log("Request = ", req);
  9. console.log("Resource = ", res);
  10. return res.status(200).json({ msg: "send to the queue!" });
  11. });
  12. //start server
  13. app.listen(process.env.PORT, () => console.log("server started!!"));


我运行了localhost并调用了后端操作,但Node API 2 docker容器中什么也没有发生。如果我遗漏了什么,请您指导我。
期待得到帮助。
谢谢你!

tjjdgumg

tjjdgumg1#

为您的Nginix尝试此代码

  1. location /api2 {
  2. add_header 'Access-Control-Allow-Origin' '*';
  3. add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
  4. add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
  5. add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
  6. proxy_pass http://api2:3004/;
  7. }

字符串

相关问题