我在一个名为backend.example.com的子域上使用laravel编写了一个API。如果我尝试从另一个名为partner.example.com的子域从我的API获取信息,我可以自己验证并获取这些信息。这是Ajax请求:
但如果我试图对名为example.com的主域做同样的事情,我会收到此错误:
无法加载https://backend.example.com/api/v1/leads/showAdmin: 对预检请求的响应没有通过访问控制检查:否 '访问控制允许来源'标题出现在请求的上 资源。起源' https://example.com'因此不允许访问。
这是主域的Ajax:
var ajaxArray = {
"fromDate": from,
"toDate": to
};
console.log(ajaxArray);
jQuery.ajax({
url: ("https://backend.example.com/api/v1/leads/showAdmin"),
type: "POST",
data: ajaxArray,
crossDomain: true,
headers : {
"Authorization": "Basic " + btoa("api@example.com" + ":" + "123456"),
"Accept": "application/json"
},
error: function() { alert("Error"); },
success: function(result){
alert("Working");
});
}});
这是来自子域的Ajax请求,它正在进行中:
var ajaxArray = {
"fromDate": from,
"toDate": to,
"table": "no",
"userID": 20
};
console.log(ajaxArray);
jQuery.ajax({
url: ("https://backend.example.com/api/v1/leads/show"),
type: "POST",
data: ajaxArray,
crossDomain: true,
headers : {
"Authorization": "Basic " + btoa("api@example.com" + ":" + "123456"),
"Accept": "application/json"
},
error: function() { alert("No"); },
success: function(result){
alert("Working");
});
}});
但是我没有得到它,因为我已经允许所有...... 见这里:
<?php
return [
/*
|--------------------------------------------------------------------------
| Laravel CORS
|--------------------------------------------------------------------------
|
| allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
| to accept any value.
|
*/
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedOriginsPatterns' => [],
'allowedHeaders' => ['*'],
'allowedMethods' => ['*'],
'exposedHeaders' => [],
'maxAge' => 0,
];
非常感谢任何帮助! 亲切的问候
答案 0 :(得分:0)
没有插件就试过了吗?它足以添加标题,只是为了查看它是否正常工作你可以尝试在一条路线上回复回复响应,即
。use Illuminate\Http\JsonResponse;
Route::get("/whatever", function() {
$response = new JsonResponse(['arr','ay']);
$response->header("Access-Control-Allow-Origin", "http://localhost:3000");
return $response;
}
您使用的是哪个版本的Laravel?