XMLHttpRequest cannot load XXX, no 'Access-Control-Allow-Origin' header
P粉574695215
P粉574695215 2023-09-21 16:34:22
0
2
499

tl;dr; About same-origin policy

I have a Grunt process that starts an instance of express.js server. This was all working perfectly fine until just now, but now it starts serving a blank page and displays the following in the error log in the developer console of Chrome (latest version):

XMLHttpRequest cannot load https://www.example.com/ There is no 'Access-Control-Allow-Origin' header on the requested resource. Therefore, access from 'http://localhost:4300' is not allowed.

What's preventing me from accessing this page?

P粉574695215
P粉574695215

reply all (2)
P粉513316221

The target server must allow cross-domain requests. In order to allow it via express, just handle the request with http options:

app.options('/url...', function(req, res, next){ res.header('Access-Control-Allow-Origin', "*"); res.header('Access-Control-Allow-Methods', 'POST'); res.header("Access-Control-Allow-Headers", "accept, content-type"); res.header("Access-Control-Max-Age", "1728000"); return res.sendStatus(200); });
    P粉953231781

    tl;dr —When you want to read data, (mostly) using client-side JS, from a different server you need the server with the data to grant explicit permission to the code that wants the data.

    There's a summary at the end and headings in the answer to make it easier to find the relevant parts. Reading everything is recommended though as it provides useful background for understanding thewhythat makes seeing how thehowapplies in different circumstances easier.

    About the Same Origin Policy

    This is theSame Origin Policy. It is a security feature implemented by browsers.

    Your particular case is showing how it is implemented for XMLHttpRequest (and you'll get identical results if you were to use fetch), but it also applies to other things (such as images loaded onto aor documents loaded into an