Force response()->download() return HTTPS url - laravel

I have switched my Laravel 5.1 to HTTPS and everything seems fine, except the file download part.
The problem is response()->download() returns a HTTP link instead of HTTPS and I get a mixed content in Chrome, so the link is blocked.
And some code:
$headers = array
(
'Content-Type' => 'application/vnd.android.package-archive'
);
return response()->download(config('custom.storage') . $apk->generated_filename, $apk->filename, $headers);

Related

Get cookies from Laravel Http Client

I'm trying to login into a service (Jasper Server API) using the Http Client, but cant get the cookies from the response
This is what I'm doing:
$response = Http::withOptions( [ 'proxy' => '' ] )->
post('192.168.52.84/jasperserver/rest_v2/login?j_username=user&j_password=password');
$cookies=$response->cookies;
dd($cookies);
The output being:
GuzzleHttp\Cookie\CookieJar {
-cookies: []
-strictMode: false
}
When I do the same Get on the browser I get the cookies fine.
What could be the problem?
You can get cookie value by the following code also, get cookie by name and then get the value.
$cookies = $response->cookies()->getCookieByName('YOUR_COOKIE_NAME')->getValue();
I finally solved it.
It was just that when I did:
post('192.168.52.84/jasperserver...')
I didn't specify the scheme:
post('http://192.168.52.84/jasperserver...')
With that, I got the cookies just right.

how to solve cors Allow Access control in vue js and laravel application

I Have tried almost everything. My front end is developed in vue js . backend is in laravel. we have written api for another website from which we are trying to fetch data. If directly access that website Url it gives all the data but when i try to access it from my website with axios it gives me this error.
Access to XMLHttpRequest at 'https://example.com/api/tickets/fetch_tickets?page=undefined' from origin 'http://localhost:8000' has been blocked by CORS policy: Request header field x-requested-with is not allowed by Access-Control-Allow-Headers in preflight response.
that website form which i am trying to fetch data also build in laravel. i have created middleware and applied it on api routes. I added chrome extension Allow Cors with which it works fine but we cant ask every client to use that extension.
We access that url from other website which is accessing data nicely. only vue js app creating these issue.
Vue Code
getTickets() {
axios.get( 'example.com/api/tickets/fetch_tickets?page=' + this.pagination.current, {
}).then((response) => {
// console.log(res.data.data)
// this.desserts = res.data.data;
// this.loadingprop = false;
this.desserts = response.data.data;
this.pagination.current = response.data.current_page;
this.pagination.total = response.data.last_page;
console.log(response.data.data);
}).catch((err) => {
this.handleErrors(err.response.data.errors);
})
.then(() => {
this.loading = false;
});
}
other website's routes
Route::group(['middleware' => ['api','cors']], function () {
Route::group(['prefix' => 'tickets'], function () {
Route::post('/store_ticket_auth', 'TicketApiController#storeTicketAuth'); //enter ticket auth
Route::get('/fetch_tickets', 'TicketApiController#fetchTickets'); //get all tickets
Route::get('/fetch_replies/{ticket_id}', 'TicketApiController#fetchTicketReplies'); // get all replies by ticket id
Route::post('/send_reply', 'TicketApiController#sendTicketReply'); // Send reply
Route::post('/update_ticket', 'TicketApiController#updateTicketStatus'); // Update Status
});
});
Do I need to add this on my cuurent project too?
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
I think the issue is on client side but dont know why it is not working.
I tried all answers on stackoverflow but nothing works
I have to add these lines in my index.php file of laravel
header("Access-Control-Allow-Origin: *");
//header("Access-Control-Allow-Methods", "DELETE, POST, GET, OPTIONS");
header("Access-Control-Allow-Headers:*");
if ($_SERVER['REQUEST_METHOD'] == "OPTIONS") {//send back preflight request response
return "";
}
Solved my issues by commenting out:
// window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
in resources/js/bootstrap.js
The error is telling you that the server won't allow the client to use a x-requested-with header.
In php you can do this to allow the server to accept that header:
header('Access-Control-Allow-Headers: X-Requested-With');
If you want the easy way you can use laravel-cors
You can follow the installation step and add this code in your config/cors.php
'allow_origins' => [
'https://yourfrontendrequest.url',
],
Install Moesif Origin & CORS Changer Chrome extension and
Then go to resources/js/bootstrap.js and comment out this line // window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
you can disable same origin policy in chrome
press win + R
and then copy this :
chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security

API call is working fine when called through Postman, but when called by the web page it bogs and returns failed

I have a laravel application that I'm creating. The web routes calls the API for information. When I test my API it returns data, but when the front end dev calls the API it slows the system and returns a failure. This is a simple GET that was working before but is not working now.
This is the the API call from the web:
$url = 'http://localHost:8000/api/v1.0/theater_movies';
$opts = array('http'=>array('http' => array(
'protocol_version' => 1.1,
'user_agent' => 'PHPExample',
'method' => 'GET',
'header' => "Content-type: application/json\r\n")
));
//Basically adding headers to the request
$context = stream_context_create($opts);
$getMovies = json_decode(file_get_contents($url,false,$context), true);
I'm getting the file_get_contents error:
file_get_contents(http://localhost:8000/api/v1.0/theater_movies): failed to open stream: HTTP request failed!
And this is the correct output from Postman

How to retrieve JSON from a API endpoint using Laravel 5.4?

I have 2 projects made with Laravel 5.4:
Prj-1 it is an Restful API that returns JSON.
Prj-2 it is an website that consumes the above endpoints.
In this way, I have the follow endpoint from Prj-1 :
myAPI.com/city that returns a list of all cities in the database in a JSON format.
Inside Prj-2 I have the follow:
Route:
Route::get('/showCityAPItest','AddressController#getcity');
Controller:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
...
public function getcity()
{
$request =Request::create('http://myAPI.com/city', 'GET');
$response = Route::dispatch($request);
dd($response);
}
If I use directly the URL (http://myAPI.com/city) in the browser, it works. I can see the JSON as expected.
BUt when I try to retrieve it from the Prj-2 I can't see it in the browser.
Actually I see
404 Not Found
nginx/1.10.1 (Ubuntu)
I was following this post but I dont know what am I doing wrong.
Any help?
Yeah, #Joel Hinz is right. Request will work within same project api end.
You need to use GuzzleHttp.
Step 1. Install guzzle using composer. Windows base operating guzzle command for composer :
composer require guzzlehttp/guzzle
step 2 write following code
public function getcity()
{
$client = new \GuzzleHttp\Client;
$data =$client->request('GET', 'http://myAPI.com/city', [
'headers' => [
'Accept' => 'application/json',
'Content-type' => 'application/json'
]
]);
$x = json_decode($data->getBody()->getContents());
return response()->json(['msg' => $x], 200);
}
The answer to which you are referring is talking about internal routes. You can't use the Request and Route facades for external addresses like that. Instead, use e.g. Guzzle (http://docs.guzzlephp.org/en/latest/) to send your requests from the second site.

Getting different status code using Laravel PHPUnit

Laravel 5.0
PHPUnit 4.8.24
If I visit my homepage route('/') in browser chrome shows me status-code 200 OK
But when I check with PHPUNIT
$response = $this->call( 'GET', '/' );
var_dump( $response->getStatusCode() );
It returns int(500) why?
There might be multiple reasons for that for example incorrect database connection. You should run:
$response = $this->call( 'GET', '/' );
var_dump($response->getContent());
or verify error log to see what's the exact problem

Resources