access-control-allow-origin javascript code example
Example 1: access-control-allow-origin nodejs express
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
Example 2: access-control-allow-origin
Access-Control-Allow-Origin: *
Example 3: cross origin even with allow header
header('Access-Control-Allow-Origin: http://localhost:8100');
header ("Access-Control-Expose-Headers: Content-Length, X-JSON");
header ("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
header ("Access-Control-Allow-Headers: Content-Type, Authorization, Accept, Accept-Language, X-Authorization");
header('Access-Control-Max-Age: 86400');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
header("HTTP/1.1 200 OK");
return;
}
Example 4: Access to XMLHttpRequest at 'http://localhost/MySQL_pracs/InsertUser.php' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
//Access to XMLHttpRequest at 'http://localhost/[api path].php' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
//The error is simply saying that "Content-Type" is missing from "Access-Control-Allow-Headers".
//Therefore we need to add "Content-Type" to "Access-Control-Allow-Headers".
<?php
header('Access-Control-Allow-Headers: Content-Type');
-----
?>
Example 5: what is cors
“CORS” stands for Cross-Origin Resource Sharing.
It allows you to make requests from one website to another website
in the browser, which is normally prohibited by another browser policy
called the Same-Origin Policy (SOP).
Example 6: header access-control particular domain
Access-Control-Allow-Origin: http: