简体   繁体   English

如何将跨域请求从客户端发送到服务器?

[英]How to send cross domain requests from client to server?

I am using Google Drive API but while retrieving data from client side I get this error: 我正在使用Google Drive API,但是在从客户端检索数据时出现此错误:

XMLHttpRequest cannot load url.  No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. 

Note that I am not allowed to change headers. 请注意,我不允许更改标题。

Is there a way to request cross domain? 有没有办法请求跨域?

var req = {
    action: 'getFiles',
};  

this.getJSON('drive.php', req, function(serverData)
{
    console_log(serverData);

});

Above code gives this error. 上面的代码给出了此错误。 How can I solve this problem? 我怎么解决这个问题?

One option: 一种选择:

var url = 'drive.php';


$.ajax({
   type: 'GET',
    url: url,
    async: false,
    jsonpCallback: 'jsonCallback',
    data: {action: 'getFiles'},
    contentType: "application/json",
    dataType: 'jsonp',
    success: function(json) {
       console.dir(json.sites);
    },
    error: function(e) {
       console.log(e.message);
    }
});

Still it gives GET error 仍然给出GET错误

You can make a request using JSONP; 您可以使用JSONP发出请求; see the following for examples. 请参阅以下示例。 http://www.sitepoint.com/jsonp-examples/ http://www.sitepoint.com/jsonp-examples/

An example from that site: 该站点的示例:

(function($) {
var url = 'http://www.jquery4u.com/scripts/jquery4u-sites.json?callback=?';


    $.ajax({
       type: 'GET',
        url: url,
        async: false,
        jsonpCallback: 'jsonCallback',
        contentType: "application/json",
        dataType: 'jsonp',
        success: function(json) {
           console.dir(json.sites);
        },
        error: function(e) {
           console.log(e.message);
        }
    });

    })(jQuery)

;

Not really. 并不是的。 The cross domain request is not allowed for security reasons. 出于安全原因,不允许跨域请求。 What you can do is the following: 您可以执行以下操作:

Write a PHP script which just forwards your request and place this PHP script in the same server as your JavaScript. 编写一个仅转发您的请求的PHP脚本,然后将此PHP脚本与JavaScript放在同一服务器上。 Your JS will thereby perform the request on the domain and will not end up with an error. 这样,您的JS将在域上执行请求,并且不会导致错误。

In php you need 在PHP中,您需要

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST/GET');

insert into header file .php, it's allow client POST data with method POST/GET to server and get receiver from it ... 插入到头文件.php中,它允许使用方法POST / GET的客户端POST数据到服务器并从中获取接收者...

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

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