简体   繁体   English

如何设置 Access-Control-Allow-Origin header?

[英]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.每当用户访问https://www.google.com/时,扩展程序都应将其记录到日志文件中。 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.我目前正在我自己的设备上开发扩展,并使用http://localhost/log.php来获取 POST 请求并将信息记录到基于 POST 信息的文件中。 My manifest is working and I have tested it.我的清单正在工作,我已经对其进行了测试。 Below is my track.js :下面是我的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 :这是我的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. log.txt是一个空文件。 I know CORS is the problem because when I open the console on https://www.google.com/ , I see this:我知道 CORS 是问题所在,因为当我在https://www.google.com/上打开控制台时,我看到了:

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.谢谢你的帮助。

You should add "Access-Control-Allow-Origin: *" on your webserver configuration (Nginx or Apache or...) that you are currently using on your localhost.您应该在您当前在本地主机上使用的网络服务器配置(Nginx 或 Apache 或...)上添加“Access-Control-Allow-Origin:*”。

You can not bypass CORS from your code or your request at all.您根本无法从您的代码或您的请求中绕过 CORS。

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

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

Apache: Apache:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM