由于CORS错误,当通过nginx服务create-react应用程序时,我无法在nodejs中调用express路由。我花了几个小时在谷歌上搜索这个问题,并查看堆栈溢出的帖子,但无法找到解决问题的方法。
我有一个react应用程序,我用npm run build
构建了它。获取请求看起来像:
let response; try { response = await fetch("https://www.mywebsite.com/api/signIn", { method: "POST", headers: { "Access-Control-Allow-Credentials": "true", "Content-Type": "application/json", }, body: JSON.stringify(userLoginInfo), credentials: "include", }); } catch (error) { ... return; }
我的快递服务器、cors设置和路线如下:
... redis configuration ... const app = express(); app.use(express.json()); // if you run behind a proxy (e.g. nginx) app.set("trust proxy", 1); // setup CORS logic const whitelist = new Set(["http://localhost:3000", "http://mywebsite.com", "https://mywebsite.com" ]); const corsOptions = { optionsSuccessStatus: 200, origin: (origin, callback) => { console.log(origin); if (whitelist.has(origin)) { callback(null, true); } else { callback(new Error("Not allowed by CORS")); } }, credentials: true, }; app.options("*", cors(corsOptions)); // ?????????????? app.use(cors(corsOptions)); app.use(session); app.use(router); app.listen(8080, () => console.log("server is running on port 8080")); router.post("/signIn", (req, res) => { const {email, password} = req.body; console.log(email, password); console.log(req.session); ... do stuff ... });
我的nginx配置:
server { index index.html index.htm index.nginx-debian.html; server_name mywebsite.com www.mywebsite.com; #I've tried adding the following 3 lines - nothing changes #add_header 'Access-Control-Allow-Origin' 'http://localhost:3000' always; #add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always; #add_header 'Access-Control-Allow-Headers' 'X-Requested-With,Accept,Content-Type, Origin' always; # react app & front-end files location / { root directoryToTheReactBuild/build; try_files $uri /index.html; } location /api/ { proxy_pass http://localhost:8080; proxy_buffering on; } #managed by Certbot listen 443 ssl; ssl_certificate /etc/letsencrypt/live/mywebsite.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/mywebsite.com/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; }
所以我在一个AWS EC2实例中完成这一切,并使用https访问我的网站。正如我所说,我已经构建了react应用程序,但我正在使用npm start
运行express服务器,直到一切正常。我现在得到的错误是:"Not allowed by CORS"
,来自express应用程序。console.log中未定义原点。
有人能告诉我我做错了什么吗?