By overwatch
Hello,
A brief description of my stack is required, i have nodejs, react on ubuntu 18.04 . I want to use nginx to redirect all API calls to api.domain.com and also serve react on domain.com or www.domain.com. Am halfway through as i have already nginx redirecting both backend and frontend; however a problem arose i can’t make api calls from the frontend to the backend. as am getting cors Errors. more specifically the resource at api.my_domain.com has been blocked by cors policy this the nginx conf of api.domain.com
location / {
proxy_pass http://localhost:5001;
proxy_http_version 1.1;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
set $cors '';
if ($http_origin ~ '^https?://(localhost|www\.cinetie\.com|cinetie\.com)') {
set $cors 'true';
}
if ($cors = 'true') {Connection reset by 206.189.238.61 port 22
more_set_headers 'Access-Control-Allow-Origin' "$http_origin" always;
D:\apps\nodejs\cinetie-backend>s-Control-Allow-Credentials' 'true' always;
more_set_headers 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
more_set_headers 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always;
# required to be able to read Authorization header in frontend
more_set_headers -s '400 422 403 404 401 500 522 503'
more_set_headers 'Access-Control-Expose-Headers' 'Authorization' always;
}
if ($request_method = 'OPTIONS') {
# Tell client that this pre-flight info is valid for 20 days
more_set_headers 'Access-Control-Max-Age' 1728000;
more_set_headers 'Content-Type' 'text/plain charset=UTF-8';
more_set_headers 'Content-Length' 0; return 204; }
So how do i fix this ?
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Yeah you have to :
install cors dependancy : npm install cors add :
app.use(cors({origin : '*'}))```
This little code is attaching cors to all of you routes to accept every domain name allowing to connect with your app
Then redeploy it…
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.