简体   繁体   English

浏览器中的“跨源请求被阻止:同源策略”错误

[英]“Cross-Origin Request Blocked: The Same Origin Policy” Error in browser

I got this error when I try to POST json file to my server.当我尝试将 json 文件发布到我的服务器时出现此错误。

On my server side, the code is:在我的服务器端,代码是:

    @POST
    @Path("updatedata")
    @Produces("text/plain")
    @Consumes("application/json")
    public Response UpdateData(String info) {
        Gson gson = new Gson();
        List<Data> list = gson.fromJson(info, new TypeToken<List<Data>>() {
        }.getType());

        int is_success = 0;
        try {
            is_success += trainingdata.updateData(list);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        String returnjson = "{\"raw\":\"" + list.size() + "\",\"success\":\"" + is_success + "\"}";
        return Response.ok().entity(returnjson).header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Methods", "POST").build();
    }

I can update my data successfully through RESTClient - a Chrome Plugin.我可以通过 RESTClient - Chrome 插件成功更新我的数据。

But when I build the frontend and try to call the API through jaascript, Firefox shows: Cross-Origin Request Blocked: The Same Origin Policy .... Chrome shows: XMLHttpRequest cannot load ... No 'Access-Control-Allow-Origin' header is present on the requested resource.但是当我构建前端并尝试通过 jaascript 调用 API 时,Firefox 显示:跨域请求被阻止:同源策略...... Chrome 显示:XMLHttpRequest 无法加载......没有'Access-Control-Allow-Origin ' 请求的资源上存在标头。 Origin '...' is therefore not allowed access Origin '...' 因此不允许访问

I wrote the javascript like this:我写了这样的javascript:

var json = JSON.stringify(array);

var xhr = new XMLHttpRequest();
xhr.open("POST", "http://myurl:4080/updatedata", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(json);

xhr.onload = function (e) {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            alert('hello');
        }
    }
};
xhr.onerror = function (e) {
    console.error(xhr.statusText);
};

Is there any problem with my javascript code?我的javascript代码有问题吗?

I deploy my backend code and front end code in the same machine.我将后端代码和前端代码部署在同一台机器上。

The GET function works successfully. GET 函数成功运行。

@GET
@Produces("application/json")
@Path("/{cat_id}")
public Response getAllDataById(@PathParam("cat_id") String cat_id) {
    ReviewedFormat result = null;
    try {
        result = trainingdata.getAllDataById(cat_id);
        Gson gson = new Gson();
        Type dataListType = new TypeToken<ReviewedFormat>() {
        }.getType();
        String jsonString = gson.toJson(result, dataListType);
        return Response.ok().entity(jsonString).header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Methods", "GET").build();

    } catch (SQLException e) {
        logger.warn(e.getMessage());
    }
    return null;
}

Front end:前端:

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://URL:4080/mywebservice/v1/trainingdata/" + cat_id, true);

xhr.onload = function (e) {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            //console.log(xhr.responseText);
            var jsoninfo = xhr.responseText;
            var obj = JSON.parse(jsoninfo);
        }
     }
}

CORS prevents issues from occurring with cross-site attacks and forces smart development by not relying on other people's resources (which could die). CORS 通过不依赖其他人的资源(可能会死)来防止跨站点攻击发生问题并强制进行智能开发。 Its a default security feature on most servers and browsers.它是大多数服务器和浏览器的默认安全功能。

In Apache you can disable CORS by adding a header, IIS and AppEngine work similarly.在 Apache 中,您可以通过添加标头来禁用 CORS,IIS 和 AppEngine 的工作方式类似。

Since you are developing locally, your best bet is either XAMPP/WAMPP plus an appropriate header - or simply switch to FireFox.由于您是在本地开发,因此您最好的选择是 XAMPP/WAMPP 加上适当的标头 - 或者干脆切换到 FireFox。

FireFox does not consider local files under CORS, while most browsers do. FireFox 不考虑 CORS 下的本地文件,而大多数浏览器会考虑。

Apache Fix :阿帕奇修复

Add header ->添加标题->

Header set Access-Control-Allow-Origin "*"

Reset Server ->重置服务器 ->

apachectl -t
  • sudo service apache2 reload须藤服务 apache2 重新加载

IIS Fix: IIS修复:

Modify web.config in root directory (similar to HTAccess)修改根目录下的web.config(类似HTAccess)

<?xml version="1.0" encoding="utf-8"?>
<configuration>
 <system.webServer>
   <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="*" />
     </customHeaders>
   </httpProtocol>
 </system.webServer>
</configuration>

App Engine :应用引擎

Header Method for Python: self.response.headers.add_header() Python 的头方法:self.response.headers.add_header()

class CORSEnabledHandler(webapp.RequestHandler):
  def get(self):
    self.response.headers.add_header("Access-Control-Allow-Origin", "*")
    self.response.headers['Content-Type'] = 'text/csv'
    self.response.out.write(self.dump_csv())

For Java : resp.addHeader()对于 Java :resp.addHeader()

public void doGet(HttpServletRequest req, HttpServletResponse resp) {
  resp.addHeader("Access-Control-Allow-Origin", "*");
  resp.addHeader("Content-Type", "text/csv");
  resp.getWriter().append(csvString);
}

For Go : w.Header().Add()对于 Go :w.Header().Add()

func doGet(w http.ResponseWriter, r *http.Request) {
  w.Header().Add("Access-Control-Allow-Origin", "*")
  w.Header().Add("Content-Type", "text/csv")
  fmt.Fprintf(w, csvData)
}

CORS issues can be bypassed via JSONP for GET requests if this interested you: http://en.wikipedia.org/wiki/JSONP如果您对 GET 请求感兴趣,可以通过 JSONP 绕过 CORS 问题: http : //en.wikipedia.org/wiki/JSONP

This is an issue caused by making a cross domain request in javascript.这是由在 javascript 中进行跨域请求引起的问题。 The browser prevents this for security reasons.出于安全原因,浏览器会阻止这种情况。

In javascript you can't make requests to a different domain (including different port) by default.在 javascript 中,默认情况下您不能向不同的域(包括不同的端口)发出请求。

Your options are to enable CORS or use a reverse proxy if you need to send requests to another domain.如果您需要向另一个域发送请求,您可以选择启用 CORS 或使用反向代理。

It sounds like you have control over the remote resource you're posting to.听起来您可以控制要发布到的远程资源。 If that's the case, your remote resource needs to have the following header:如果是这种情况,您的远程资源需要具有以下标头:

Access-Control-Allow-Origin: http://yourrequestingurl.com

More information here (It looks like someone asked a question like yours already): Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at更多信息在这里(看起来有人已经问过像你这样的问题): 跨源请求被阻止:同源策略不允许在以下位置读取远程资源

Thanks for @TGH's hint, I finally solve the problem by adding a web proxy.感谢@TGH 的提示,我终于通过添加网络代理解决了问题。

Refer to Using a Web Proxy , I create a proxy.php file, which receive Javascript's xmlHttpRequest, get the postdata and call the web service API.请参阅使用 Web 代理,我创建了一个 proxy.php 文件,该文件接收 Javascript 的 xmlHttpRequest,获取 postdata 并调用 Web 服务 API。

<?php

$method = isset($_POST['method']) ? $_POST['method'] : 'POST';
$postData = file_get_contents('php://input');
$url = $envArray['url'] . ':' . $envArray['port'] . '/mywebservice/v1/trainingdata/updatedata';

echo curl($url, $postData, $method);
}

function curl($url = '', $params = '', $method = 'POST'){
    if (empty($url)) {
        error_log('Curl URL is empty.');
        return;
    }
    $envArray = Settings::getEnvAry();

    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);                                                                     
    curl_setopt($ch, CURLOPT_POSTFIELDS, html_entity_decode($params, ENT_QUOTES));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
            'Content-Type: application/json',                                                                                
            'Content-Length: ' . strlen($params)
        )                                                                       
    );
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      

    $response = curl_exec($ch);
    $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $rs = array('status' => $http_status, 'response' => $response);

    return json_encode($rs);
}
?>

And in the front end, I call the proxy.php在前端,我调用了 proxy.php

 var xhr = new XMLHttpRequest();
    xhr.open("POST", "proxy.php", true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.send(json);

I think this is better for deploy project onto remote box, instead of modifying Apache configuration.我认为这更适合将项目部署到远程框,而不是修改 Apache 配置。

You can add header in your Nginx configuration and similarly in other web servers您可以在 Nginx 配置中添加标头,并在其他 Web 服务器中类似

example例子

add_header Access-Control-Allow-Origin *;

暂无
暂无

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

相关问题 跨域请求被阻止:“相同来源策略”不允许读取远程资源 - Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource a 为什么我收到跨域请求被阻止的原因:同源策略禁止读取远程资源 - Why do I get a Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource 跨源请求被阻止:同源策略不允许读取远程资源 - react js - Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource - react js Cross-Origin Request Blocked:同源策略不允许读取远程资源。 CORS 预检响应未成功 - Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource. CORS preflight response did not succeed Cross-Origin Request Blocked:同源策略不允许读取远程资源。 (原因:CORS 预检响应没有成功) - Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource. (Reason: CORS preflight response did not succeed) 跨域请求被阻止:同源策略不允许读取位于 https://localhost:8000/users/login 的远程资源 - Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:8000/users/login AJAX请求跨域请求被阻止错误 - AJAX request Cross-Origin Request Blocked error axios post request retrning error: Cross-Origin Request Blocked - axios post request retrning error: Cross-Origin Request Blocked 如何解决Firefox中的跨域请求阻止错误 - How to solve Cross-Origin Request Blocked error in firefox goodreads API 导致跨域请求被阻止:javascript 中的错误 - goodreads API gives Cross-Origin Request Blocked: error in javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM