Search code examples
phpxmlhttprequest

How can I set the Access-Control-Allow-Origin header?


I know this is a really simple question, but after searching a lot I can't find how to set headers.

Here's what I want to do:

Whenever the user goes to https://www.google.com/, then an extension should log that into a logfile. I currently am developing the extension on my own device, and using http://localhost/log.php to get POST requests and log information to files based on the information POSTed. My manifest is working and I have tested it. Below is my track.js:

function log(info){
    var xhttp=new XMLHttpRequest();
    xhttp.onreadystatechange=function(){
        if(this.readyState===4&&this.status===200){
            console.log(this.responseText);
        }
    }
    xhttp.open("POST","http://localhost/log.php",true);

    // xhttp.setRequestHeader("Access-Control-Allow-Origin","*");
    // above: my first attempt to set a header (did not work)

    xhttp.send("log_info="+info);
}
if(location.href==="https://www.google.com/")log("We're at google.com!");

This is my log.php:

<?php
header("Access-Control-Allow-Origin: *");
if(isset($_POST["log_item"]))
    file_put_contents("log.txt", $_POST["log_item"]."\n",FILE_APPEND);

And log.txt is an empty file. I know CORS is the problem because when I open the console on https://www.google.com/, I see this:

Access to XMLHttpRequest at 'http://localhost/log.php' from origin 'https://www.google.com' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

POST http://localhost/log.php net::ERR_FAILED

This seems really simple to me but I can't find how to set headers. Thanks for any help.


Solution

  • You should add "Access-Control-Allow-Origin: *" on your webserver configuration (Nginx or Apache or ...) that you are currently using on your localhost.

    You can not bypass CORS from your code or your request at all.

    For nginx (/etc/nginx/nginx.conf):

    https://enable-cors.org/server_nginx.html

    Apache:

    https://enable-cors.org/server_apache.html