问题:
我正在向Laravel API发出get请求并收到以下错误
阻止跨源请求:同源策略禁止读取 http://www.example.com/exceptions-company-reports处的远程资源。 (原因:CORS标题'Access-Control-Allow-Origin'缺失)
我在本地然后在开发服务器上关注these instructions,但我无法弄清楚为什么我只在开发服务器上遇到此问题。我甚至确认已启用php_zip
和php_xml
。
我的日志中没有错误。
客户端角色代码
getExceptionsReport: function getExceptionsReport() {
var apiBase = apiUrl + 'exceptions-company-reports';
var config = {
responseType: 'blob'
};
return $http.get(apiBase, config);
}
服务器端:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\PublishCompanyreportingRequest;
use DB;
use Auth;
use Excel;
class CompanyreportingController extends Controller {
public function __construct() {
$this->middleware( 'jwt.auth' );
$this->middleware( 'role:company-reports' );
}
public function exceptionsCompanyReports( PublishCompanyreportingRequest $requestData ) {
$list = DB::table( 'exceptions_reports' )->select('created_at','account_number','customer_name','fp','seriel_number','comment','grade','item_number','description')->get();
$rows = array();
foreach($list as $item) {
$rows[] = array(
"Received" => $item->created_at,
"Account Number"=> $item->account_number,
"Customer Name" => $item->customer_name,
"FP"=> $item->fp,
"Serial Number" => $item->seriel_number,
"Comment" => $item->comment,
"Grade" => $item->grade,
"Item Number" => $item->item_number,
"Description" => $item->description,
);
}
Excel::create('Filename2', function($excel) use($rows) {
// Set the title
$excel->setTitle('Company| Company Report');
// Chain the setters
$excel->setCreator('Company')
->setCompany('Company');
$excel->sheet('Exceptions Report', function($sheet) use($rows) {
$sheet->fromArray($rows);
$sheet->row(1, function($row) {
// call cell manipulation methods
$row->setBackground('#DDDDDD');
$row->setFontFamily('Calibri');
$row->setFontSize(14);
});
$sheet->setStyle(array(
'font' => array(
'name' => 'Calibri',
'size' => 14
)
));
});
// Call them separately
$excel->setDescription('A demonstration to change the file properties');
})->download('xlsx');
}
}
答案 0 :(得分:2)
Laravel-Excel不会为您添加标题。因此,为了避免CORS问题,请添加此标头:
Excel::create('Contactos', function($excel) use ($results) {
...
})->export('xlsx', ['Access-Control-Allow-Origin'=>'*']);
答案 1 :(得分:1)
我想出了各种各样的工作,我觉得比解决方法好一点,因为代码没有任何问题。
我决定将文件保存到服务器,然后将该文件作为响应发送,而不是依赖扩展来执行此操作。仍然非常令人沮丧,因为我永远不会真正知道错误是什么。令我更沮丧的是,我知道它可以像在我当地一样工作。我不会将此答案标记为正确,直到有人有更好的答案为止。
Excel::create('Filename2', function($excel) use($rows) {
// other code
})->save('xlsx');
return response()->file(storage_path().'/exports/Filename2.xlsx');
我也在使用DELETE
请求后立即删除该文件
public function destroy( $id ) {
\File::Delete(storage_path().'/exports/Filename2.xlsx');
return response()->json( [ 'success' => 'Report has been removed from server' ], 200 );
}
答案 2 :(得分:1)
就我而言,它的发生是因为它没有安装zip扩展名。
它向我显示跨域请求被阻止,但这不是错误