Back to articles
CORS Explained: Why Your Frontend Cannot Talk to Your API

CORS Explained: Why Your Frontend Cannot Talk to Your API

via Dev.to WebdevYoung Gao

Your React app calls your Express API. Chrome blocks the request. The error says "No Access-Control-Allow-Origin header." You add cors() and it works. But do you know what actually happened? What CORS Is Cross-Origin Resource Sharing. Browsers block requests from one origin (domain:port) to another by default. CORS headers tell the browser which cross-origin requests to allow. Same origin: same protocol + domain + port. http://app.com:3000 and http://app.com:4000 are different origins. Preflight Requests For non-simple requests (PUT, DELETE, custom headers, JSON content-type), the browser sends an OPTIONS request first. If the server responds with the right CORS headers, the browser proceeds with the actual request. OPTIONS /api/users HTTP / 1.1 Origin : http://localhost:3000 Access-Control-Request-Method : POST Access-Control-Request-Headers : content-type, authorization Proper CORS Configuration import cors from " cors " ; app . use ( cors ({ origin : [ " https://app.example.com " ,

Continue reading on Dev.to Webdev

Opens in a new tab

Read Full Article
9 views

Related Articles