Pinterest CORS error when retrieving picture - xmlhttprequest

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.

Related

Xero Authentication in WordPress

I have a client that wants to be able to create xero invoices from a custom backend plugin that I have created in WordPress. I understand the xero api docs and what data to pass to the api to create a new invoice but I have to somehow authenticate the user so that they can send data to the api. So far I have created my xero app with a client id and client secret which I believe is required to help authenticate the api request.
But how can I authenticate the api request?
If I do simple request like this it fails:
jQuery(document).ready(function ($) {
$.ajax({
url: 'https://api.xero.com/connections',
error = (res) => {
console.log(res);
},
success = (res) => {
console.log(res);
}
});
});
I'd first recommend using the official xero PHP sdk, however I'm not sure if you are able to import packages to Wordpress like this. I've done some wordpress but I know there are some limitations with importing certain external libraries.
https://github.com/XeroAPI/xero-php-oauth2
However as an alternate solution, theres a recent blogpost on using a raw OAuth2.0 library to connect to XeroAPI manually though. This might set you on the right direction!
https://medium.com/#sid.maestre/use-php-to-connect-with-xero-31945bccd037

Laravel Access to XMLHttpRequest error how to fix

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.

Why can't add headers to axios.get?

I'm using axios and vue.js to play with the Fortnite Tracker API.
In their documentation it's clearly said that we need to include the "TRN-Api-Key" in header.
I tested with Postman and It works.
And this is my axios function to make the request:
let url = `https://api.fortnitetracker.com/v1/profile/${this.platform}/${this.username}`;
// username and platform are from my Vue Component.
axios.get(url, {
headers: {
"TRN-Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxx" // of course from my account on their website.
}
})
.then(response => console.log(response.data))
I expect the output in json like in Postman but I had a 404 Error: "Network Error".
And in the Browser Network Debug I can't see the request header 'TRN-Api-Key'.
[EDIT]
If your app is running on a server you can write a short PHP-Script and use curl in it to access the API (I think it's even possible to generate PHPcode from Postman).
Just address this script with axios and submit your platform and usernameproperties to build the right url.
Or have a look at this post alternatively. Maybe the use of an other API like #kecinotrab provided in the acceptet answer will help you too.

Servicestack Windows Universal Social Authentication

I am trying to implement social authentication from a c# client within a windows universal 8.1 app. When I post to the auth provider .../googleoauth for example the client fails. Fiddler is showing a 302 redirect so the deserialization fails n the response. The authentication flow works if I use a browser so I think everything is configured correctly, but of course could have missed something. If anyone has any insight or an example using social authentication providers from a c# client that would be much appreciated.
ian
The OAuth flow requires a browser to work in order to redirect the user to the remote OAuth website where they can approve access. So you'll need to launch the url in a WebView then capture the Session cookies after the user approves your application and is redirected back to your website.
The TechStacks Auth Example demonstrates this strategy using Xamarin.Auth component for Xamarin.Android.
Just in case anyone else was looking for a sample in UWP. This seems to be working for me. The CreateCookieContainer method for the most part simply loops through the cookies and adds them to a new container that is returned. Thanks #mythz again for the awesome work and support in ServiceStack
// Grab auth cookies from callback uri
var cookies = _httpFilter.CookieManager.GetCookies(uri);
var authCookies = cookies.AsEnumerable().Where(x => new[] {"ss-id", "ss-pid", "ss-opt"}.Contains(x.Name))
.Select(x => new Cookie(x.Name, x.Value, x.Path, x.Domain)).ToArray();
string sessionId = null;
var cookieJar = CreateCookieContainer(authCookies, uri, ref sessionId);
// Store the tokens for autologin
await DataServiceFactory.Instance.StoreSingletonSetAsync(authCookies);
// Set auth on the current client
_serviceClient.CookieContainer = cookieJar;
_serviceClient.SessionId = sessionId;

Querying data remotely using New Relic API throwing "404 error"

Im using the following AJAX request to send request to New Relic, however its always throws "404 Not Found" error.
Following is the code:
var client = new XMLHttpRequest();
client.open("GET", "https://insights-api.newrelic.com/v1/accounts/REMAINING.URL", true);
client.setRequestHeader("Accept", "application/json");
client.setRequestHeader("X-Query-Key", "QUERY.KEY");
client.send();
Since the origin of the XMLHttpRequest (XHR) or Ajax is different to the requested API's URL, Cross-origin resource sharing (CORS) prevents from accessing the API. Hence, this doesn't work. To implement this, the API will have to be requested by the back-end via .NET, JAVA, PHP, Python, etc. any server side technology and the result will have to be sent to the client Ajax calls.