1
我正在使用jquery從我正在構建的Mojolicious :: Lite API中獲取一些數據。但我無法通過ajax從API接收任何數據。我可以通過curl獲取數據。 更新:我可以在同一個域上通過ajax獲取數據。這是一個CORS問題。CORS:總是通過jQuery.ajax得到Mojolicious :: Lite的空響應
這裏是我的客戶端代碼:
$.ajax({
type: 'POST',
url: 'http://localhost:3000/path',
data: JSON.stringify({ foo: 'foo', bar: 'bar' }),
dataType: 'json',
contentType: 'application/json',
beforeSend: function(xhr){
xhr.setRequestHeader('Accept', 'application/json');
}
});
這裏的API代碼:
#!/usr/bin/perl -w
use Mojolicious::Lite;
use strict;
options '*' => sub {
my $self = shift;
$self->res->headers->header('Access-Control-Allow-Origin'=> 'http://localhost:7000');
$self->res->headers->header('Access-Control-Allow-Credentials' => 'true');
$self->res->headers->header('Access-Control-Allow-Methods' => 'GET, OPTIONS, POST, DELETE, PUT');
$self->res->headers->header('Access-Control-Allow-Headers' => 'Content-Type, X-CSRF-Token');
$self->res->headers->header('Access-Control-Max-Age' => '1728000');
$self->respond_to(any => { data => '', status => 200 });
};
post '/path' => sub {
return $_[0]->render(json => {hello => "world"});
};
app->start;
這裏是所有的請求頭和數據:
OPTIONS /path
:
Request headers:
OPTIONS /path HTTP/1.1
Host: localhost:3000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:20.0) Gecko/20.0 Firefox/20.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: pt-br,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
DNT: 1
Origin: http://localhost:7000
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Response headers:
HTTP/1.1 200 OK
Connection: keep-alive
Access-Control-Allow-Headers: Content-Type, X-CSRF-Token
Access-Control-Allow-Credentials: true
X-Powered-By: Mojolicious (Perl)
Date: Sun, 25 Nov 2012 14:45:19 GMT
Access-Control-Allow-Origin: http://localhost:7000
Access-Control-Allow-Methods: GET, OPTIONS, POST, DELETE, PUT
Content-Length: 0
Access-Control-Max-Age: 1728000
Content-Type: text/html;charset=UTF-8
Server: Mojolicious (Perl)
POST /path
:
Request headers:
POST /path HTTP/1.1
Host: localhost:3000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:20.0) Gecko/20.0 Firefox/20.0
Accept: application/json
Accept-Language: pt-br,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
DNT: 1
Content-Type: application/json; charset=UTF-8
Referer: http://localhost:7000/
Content-Length: 24
Origin: http://localhost:7000
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Response headers:
HTTP/1.1 200 OK
Connection: keep-alive
Content-Type: application/json
X-Powered-By: Mojolicious (Perl)
Date: Sun, 25 Nov 2012 14:45:19 GMT
Content-Length: 17
Server: Mojolicious (Perl)
Request data: {"foo":"foo","bar":"bar"}
Response data:
不知道問題出在我的JS或Perl代碼上。 更新:可能在JS代碼上。 更新:
CORS似乎沒問題。