已配置正确域名仍出现CORS跨域错误求助
Hey there, sorry you're stuck with this annoying CORS issue—let's break it down and work through it together!
First, let's lay out the exact error you're hitting:
Access to fetch at 'https://sample.company.com/api' from origin 'https://www.company.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Even though you said this is the same project, browsers treat https://www.company.com and https://sample.company.com as separate origins (subdomains count as distinct origins in CORS rules). That's why the browser is throwing this block even if you thought your domain setup was correct.
Here are some actionable steps to fix this:
- Double-check your backend's CORS configuration: Make sure
https://www.company.comis explicitly included in theAccess-Control-Allow-Originheader. Typos are super common here—like forgetting thewwwor usinghttpinstead ofhttps(since your origin uses HTTPS). - Validate preflight request handling: Since this is a POST request, your browser will likely send an OPTIONS "preflight" request first to check permissions. Your backend needs to properly respond to this OPTIONS request with the right CORS headers (like
Access-Control-Allow-MethodsandAccess-Control-Allow-Headers) alongside the origin header. If the backend ignores OPTIONS requests, the preflight fails and the actual POST gets blocked. - Use a reverse proxy or relative paths (if possible): Since this is the same project, you could set up a reverse proxy on your
www.company.comserver that forwards/apirequests tosample.company.com/api. Then your frontend can use a relative path like/apiinstead of the full cross-domain URL—this skips CORS entirely because the request stays within the same origin. - Skip
no-corsunless you have to: The error mentions settingmode: 'no-cors', but this gives you an opaque response that you can't read the content of. Only use this if you don't need to process the API's return data (like uploading a file where you only care about success/failure status).
Hope these tips help you get past the CORS block smoothly!
备注:内容来源于stack exchange,提问作者karvai

