Laravel Access to XMLHttpRequest error how to fix - xmlhttprequest

I have a Laravel 7 application and I'm trying to access an external URL in a Bootstrap model window. When I use the below jQuery function, on button click, I want to load the model and show the external website.
$('#myModal').on('show.bs.modal', function (e) {
$(this).find('.modal-body').load('http://***.com');
});
I get the bellow error.
Access to XMLHttpRequest at 'http://****' from origin 'http://****'
has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: Redirect is
not allowed for a preflight request.
I have searched and found one solution to use middleware. I created the middleware file in app\http\Middleware\Cors.php.
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods',
'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers',
'Accept,Authorization,Content-Type');
}
After that I have added the following in app\http\Kernel.php.
protected $middleware = [
....
...
\App\Http\Middleware\Cors::class,
];
But I still get the same error. How can I fix this error?

Laravel 7 has been released in March and provides built-in support for CORS so developers don't need to use third-party packages to enable CORS in their Laravel apps.
You can use config/cors.php file for your cors settings.
For more details please follow the link - https://www.techiediaries.com/laravel/laravel-7-6-cors-example-and-tutorial/

Since you didn't explicitly mention it I'll assume you didn't do this:
you have to enable CORS for every route you want to use it with.
According to:
https://github.com/fruitcake/laravel-cors

There can be CORS on Both side on
1 API side at external URL. ( this you cannot change)
2 At your bootstrap Laravel application.( this you can change)
$('#myModal').on('show.bs.modal', function (e) {
$(this).find('.modal-body').load('http://***.com');
});
This is just a Jquery code. Can you convert this code to some server side language like php?
Remember CORS can be overridden by server side code.

Related

Unable to make HTTP post request to .NET Core MVC

I'm currently working on a project where I'm using ASP.NET Core MVC (views are running on another port using Vue). I have set up my models and controller set up and I've tested these using swagger. They work exactly as expected. I have tested the post method on swagger and it works, but requests from my view on another port running Vue and Postman return a 405 error. Inspecting the response headers on Postman, I can see "Allow : DELETE, GET, PUT". Because my view will be running on another port, I've already added CORS the following to my startup configure method (not currently concerned about security implications):
app.UseCors(builder => {
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
My controller features the following for the POST method:
[ResponseType(typeof (Review))]
[HttpPost]
public async Task Post(Review review)
{
db.Reviews.Add(review);
await db.SaveChangesAsync();
}
I am accessing the URL on Postman from https://localhost:44334/reviews/Post. Reviews being the controller and post is the method. I am not receiving any cross original control errors, just this 405. Why might it be doing this and how can I debug this?
I was trying to post to https://localhost:44334/reviews/Post but my router was not set up like this. Changing the URL to https://localhost:44334/reviews/ and setting the method to Post worked and returned a success 200 response.
It is very common issue. For requests coming from localhost AllowAnyOrigin() doesn't work. You need to allow the origin explicitly like:
services.AddCors(options => options.AddPolicy("ApiCorsPolicy", builder =>
{
builder.WithOrigins("http://localhost:8080").AllowAnyMethod().AllowAnyHeader();
}));
In the configure method tell CORS to use the policy you just created:
app.UseCors("ApiCorsPolicy");
Requests from postman passes the CORS because they attach special headers.

No 'Access-Control-Allow-Origin' header when launch ajax in vue component under electron-vue dev envrironment

Following https://github.com/SimulatedGREG/electron-vue, i run yarn run dev and make a minor change to see how it works.
In electron vue application, i have launch an ajax request in vue component created hook function,
created: function () {
let self = this
this.$http.get('http://example.com/api/hwid/383').then(
function (resp) {
self.title = resp.title
}
)
}
In the vue-electron dev tool, there are following error in the console:
XMLHttpRequest cannot load http://example.com/api/hwid/383. No 'Access- Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9080' is therefore not allowed access.
How to solve that?
Must i set the cross domain in the server side?
Yes, you should add Access-Control-Allow-Origin for localhost on the server side.
Since it's only a browser policy, you eventually can write your own (proxy) server which will get http://example.com/api/hwid/383 data. Then you will request data through your server without any issues.

I am using vue-resource with vue cli webpack i have 'Access-Control-Allow-Origin' issue

mounted(){
this.$http.get('http:anotherurl.com/api/data.xml')
.then(function (response) {
console.log(response);
});
}
i get this console error :
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
i test vue-resource with reddit and it worked fine but with this url gives the problem . please help .
The people who set up anotherurl.com have configured it to not allow requests via JavaScript from sites other than their own. This is a feature of HTTP / CORS.
For further reading, the Mozilla documentation explains a little more about what is going on:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Access-Control-Allow-Origin
If you are using chrome you can get an extension to ignore xframe-headers. don't know how to solve it in production though
I would say that as vue-resource is deprecated from 2.0 v you should look at newer API like this one here - https://github.com/mzabriskie/axios
Axios is powerful-promise based HTTP client for the browser and node.js

Pinterest CORS error when retrieving picture

For a project, I retrieve pictures from multiples Social Network. I use Pinterest, and I can list the pins and display them with the URL. But when I want to download a picture with an XMLHttpRequest, I receive a CORS error.
Is it because of the policy of Pinterest or is there an other way to do I?
Here is my code
console.log("Url de l'image: " + this.snURL);
//bug avec Pinterest
var xhr = new XMLHttpRequest();
var _self = this;
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function () {
console.log(reader.result);
_self.initRealisationLocalStorage();
workInProgress.Start('Traitement de l\'image');
workInProgress.Info('Traitement de l\'image');
$scope.uploadPhotoNotLocalstorage(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', this.snURL);
//xhr.setRequestHeader("Access-Control-Allow-Origin","*");
xhr.responseType = 'blob';
xhr.send();
});
If someone have a solution or ran explaination I'll be happy to hear it
When calling another domain from a browser directly (javascript) there is a security to prevent arbitrary inclusion of external data.
When this is allowed, it is normally the server who define the CORS header "Access-Control-Allow-Origin" but I guess this is not acceptable for Pinterest to add every domains calling their API.
For that they recommend to use their SDK here and it will use the redirect url you configure in your Pinterest App. as a fallback, otherwise they will use the postMessage API
I don't think you can just make AJAX calls straight to their API from your JavaScript for this reason (CORS restriction on the browser side), see this post.
Another possibility is to create a proxy backend on your side (like a node.js project) which make the query to the Pinterest API and then you query that proxy on your side from your Javascript AJAX
You will not have CORS issue as the backend called would be on your side, and even it is deployed in a different domain you can set the CORS headers on that backend yourself.
I think the SDK way would address you issue and it looks to be the only way to do it when calling the API from a browser directly.

ionic yii2 Response for preflight has invalid HTTP status code 500

I have a Ionic App and I'm trying to do a POST:
$http({
url: url+'/usuario/log',
method: 'POST',
data: {usuario : $scope.data.usuario, senha:$scope.data.senha},
headers : {'content-type':'application/json; charset=UTF-8'}
}).then(function(result) { ... });
On the server side I have a Yii2 application:
public function actionLog(){
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: *");
header("Access-Control-Allow-Headers: content-type");
$params = json_decode(file_get_contents('php://input'),true);
$usuario = $params['usuario'];
$senha = $params['senha'];
...
}
But the error I got is always this, I send a POST and get a OPTIONS
OPTIONS http://www.nexusolucoes.com.br/personal/web/usuario/log
XMLHttpRequest cannot load http://www.nexusolucoes.com.br/personal/web/usuario/log. Response for preflight has invalid HTTP status code 500
The problem seems to be related with CORS, if the backend is on a different domain than the frontend the browser will always send an OPTIONS request first, to confirm that the cross domain sharing is allowed for the frontend domain.
If the browser gets a proper response for the OPTIONS, then, the POST request (the one you want) will be triggered as usual.
To sum up, you need to: Add a mapping on the URL Manager to respond to the OPTIONS verb for the exact same URL where you're sending the POST. Then, you need to create an action within a controller or to use the Yii's yii\rest\OptionsAction along with the CORS filters to allow the frontend domain to make the POST request.
Please check the following links for more information:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
http://www.yiiframework.com/doc-2.0/yii-filters-cors.html
http://www.yiiframework.com/doc-2.0/guide-rest-controllers.html