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

ruyhziif  于 4个月前  发布在  Nginx
关注(0)|答案(1)|浏览(92)

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

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

字符串
我的Nginx配置是:

server {
    listen 80;
    
    location /api {

        #rewrite ^/api$ /api/ permanent;
        #rewrite ^/api/(.*)$ /$1 break;
  
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
  
        #add_header Access-Control-Allow-Origin *;
        #add_header Access-Control-Max-Age 3600;
        #add_header Access-Control-Expose-Headers Content-Length;
        #add_header Access-Control-Allow-Headers Range;

        proxy_pass_request_headers on;
  
        proxy_pass http://nestbackend:3000/;
        #this is NestJS I have already implemented app.enableCors();
    }

    location /api2 {
        proxy_pass http://api2:3004/;
    }

    location / {

        proxy_pass http://frontend:3003/;
    }
}


我的NodeJS api 2是:

const express = require("express");
const app = express();
let cors = require("cors");
require("dotenv").config();

app.use(cors());

app.post("/graphql", async (req, res) =>{
    console.log("Testing CORS!!!!!!!!");
    console.log("Request = ", req);
    console.log("Resource = ", res);
    return res.status(200).json({ msg: "send to the queue!" });
});

//start server
app.listen(process.env.PORT, () => console.log("server started!!"));


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

tjjdgumg

tjjdgumg1#

为您的Nginix尝试此代码

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

字符串

相关问题