Angular fetch vine thumbnail - javascript

I attempt to fetch vine thumbnail following their doc with the following code:
<!-- language: lang-js -->
var onGetVineThumbnailSuccess = function( videoUrl ) {
return function( response ) {
var args = { videoUrl: videoUrl };
args.thumbnailUrl = response['thumbnail_url']; // jshint ignore:line
$rootScope.$broadcast( 'event:onGetVineThumbnailSuccess', args);
};
};
var getVineThumbnail = function ( videoUrl ) {
$http
.get( 'https://vine.co/oembed.json?url=' + encodeURIComponent( videoUrl ) )
.then( onGetVineThumbnailSuccess( videoUrl ) );
};
but in the console I've this error:
XMLHttpRequest cannot load https://vine.co/oembed.json?url=https%3A%2F%2Fvine.co%2Fv%2FeV1mMuab7Mp. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.
By the way this link: https://vine.co/oembed.json?url=https%3A%2F%2Fvine.co%2Fv%2FeV1mMuab7Mp works. If I put directly to browser's url bar. I obtain this JSON:
{
"version": 1.0,
"type": "video",
"cache_age": 3153600000,
"provider_name": "Vine",
"provider_url": "https://vine.co/",
"author_name": "Evengelia",
"author_url": "https://vine.co/u/1204040590484971520",
"title": "Everything was beautiful on this day. #6secondsofcalm",
"thumbnail_url": "https://v.cdn.vine.co/r/videos/59734161E81269170683200901120_45a46e319ea.1.1.8399287741149600271.mp4.jpg?versionId=tc3t.oqGtjpJNlOX1AeM1CAnWONhbRbQ",
"thumbnail_width": 480,
"thumbnail_height": 480,
"html": "<iframe class=\"vine-embed\" src=\"https://vine.co/v/eV1mMuab7Mp/embed/simple\" width=\"600\" height=\"600\" frameborder=\"0\"><\/iframe><script async src=\"//platform.vine.co/static/scripts/embed.js\"><\/script>",
"width": 600,
"height": 600
}
Sounds as CORS issue. But as I've no control on Vine, how should I call this service?

Access-Control-Allow-Origin is set on the response from server, not on client request to allow clients from different origins to have access to the response.
In your case, http://www.vine.co/ does not allow your origin to have access to the response. Therefore you cannot read it.
For more information about CORS: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
But, The Chrome Webstore has an extension that adds the 'Access-Control-Allow-Origin' header for you when there is an asynchronous call in the page that tries to access a different host than yours.
The name of the extension is: "Allow-Control-Allow-Origin: *" and this is the link: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi

Related

Cannot get response header fetch request even with Access-Control-Expose-Headers

I am trying to get the x-total-count response header from a fetch JS request, I have included Access-Control-Expose-Headers as advised in other previous posts and I am still unable to get the response header, I can see it is being received in chrome dev tools and have tried response.headers.get('x-total-count'); and iterating over response.headers with no luck.
What am I missing here?
async function postData() {
const myPost = {
"listingType":"Sale",
"propertyTypes": [
"townhouse",
"duplex",
"semiDetached",
"studio",
"townhouse",
"villa",
"ApartmentUnitFlat",
"Rural",
"house"
],
"geoWindow": {
"box": {
"topLeft": {
"lat": aNorth,
"lon": aWest
},
"bottomRight": {
"lat": aSouth,
"lon": aEast
}
},
},
"pageNumber": pageNumber,
"pageSize": 100
}
const options = {
method: 'POST',
body: JSON.stringify(myPost),
headers: {
'Content-Type': 'application/json',
"X-API-Key": "API-KEY",
'Access-Control-Expose-Headers': 'x-total-count'
}
};
const response = await fetch('https://api.domain.com.au/v1/listings/residential/_search', options)
if (!response.ok) {
const message = `An error has occured: ${response.status}`;
throw new Error(message);
}
const totalCount = response.headers.get('x-total-count');
for (var pair of response.headers.entries()) { console.log(pair[0]+ ': '+ pair[1]); }
console.log(totalCount)
As an updated I contacted the team that runs this API and received the following response below, turns out it was an issue on their end.
It would appear you've run into an issue with our early support for
CORS requests, the header you are trying to set,
Access-Control-Expose-Headers, is actually one that we specify from
our side.
Presently we don't specify it completely, so the x-total-count header
is not exposed to browsers which follow the CORS rules.
I have added this issue to our backlog to be rectified as soon as
possible, and it will most likely will be part of our first planned
update in early January 2021.

Unexpected token 'export' error messsage on JavaScript project

I was trying to copy a JavaScript code that I wrote on a online learning platform.
The code was 2 JavaScript files: Export and Import files.
updated: I tried adding to index.html: type = "module" to both JavaScript files
When I am running the src files now on VS code and using live server. It gives me some error messages on Chrome:
Failed to load resource: the server responded with a status of 404 (Not Found) airplane:1
When not on live server - Open index.html on chrome gives me the following error messages:
Access to script at 'file:///C:/web%20development/studies/frontend/js/test/src/missionControl.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
missionControl.js:1
Failed to load resource: net::ERR_FAILED
index.html:1 Access to script at 'file:///C:/web%20development/studies/frontend/js/test/src/airplane.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
airplane.js:1 Failed to load resource: net::ERR_FAILED
html code
<body>
<script type = "module" src="./src/missionControl.js"></script>
<script type = "module" src="./src/airplane.js"></script>
</body>
</html>
airplane.js
export let availableAirplanes = [
{name: 'AeroJet',
fuelCapacity: 800,
availableStaff: ['pilots', 'flightAttendants', 'engineers', 'medicalAssistance', 'sensorOperators'],
maxSpeed: 1200,
minSpeed: 300
},
{name: 'SkyJet',
fuelCapacity: 500,
availableStaff: ['pilots', 'flightAttendants'],
maxSpeed: 800,
minSpeed: 200
}
];
export let flightRequirements = {
requiredStaff: 4,
requiredSpeedRange: 700
};
export function meetsStaffRequirements(availableStaff, requiredStaff) {
if (availableStaff.length >= requiredStaff) {
return true;
} else {
return false;
}
};
export function meetsSpeedRangeRequirements(maxSpeed, minSpeed, requiredSpeedRange) {
let range = maxSpeed - minSpeed;
if (range > requiredSpeedRange) {
return true;
} else {
return false;
}
};
export default meetsSpeedRangeRequirements;
missionControl.js
import{ availableAirplanes, flightRequirements, meetsStaffRequirements } from './airplane';
import meetsSpeedRangeRequirements from './airplane';
function displayFuelCapacity() {
availableAirplanes.forEach(function(element) {
console.log('Fuel Capacity of ' + element.name + ': ' + element.fuelCapacity);
});
}
displayFuelCapacity();
function displayStaffStatus() {
aircavailableAirplanesrafts.forEach(function(element) {
console.log(element.name + ' meets staff requirements: ' + meetsStaffRequirements(element.availableStaff, flightRequirements.requiredStaff) );
});
}
displayStaffStatus();
function displaySpeedRangeStatus() {
availableAirplanes.forEach(function(element) {
console.log(element.name + ' meets speed range requirements:' + meetsSpeedRangeRequirements(element.maxSpeed, element.minSpeed, flightRequirements.requiredSpeedRange));
});
}
displaySpeedRangeStatus();

Serverless CORS preflight request failed - AWS API Stripe

I have spent about 2 weeks trying to debug this but no luck.
I have created a lambda function using python that creates a charge. This works fine with Stripe Checkout's simple script. It invokes it and returns the response without any issues (Python).
try:
stripe.api_key = "*******PRIVATE KEY***********"
Tokenstring = event.get('body')
Stripe_List = Tokenstring.split('=')
Token = Stripe_List[1].split('&')[0]
Email = Stripe_List[-1]
Email = Email.replace('%40', '#')
charge = stripe.Charge.create(
amount=100,
currency="gbp",
description="Example charge",
source=Token,
receipt_email=Email
)
print('Full SUCCESSFUL Transaxn Info ==== {}'.format(event))
return {
"statusCode": 302,
"headers": {
"Location": "https://example.com/#success"
}
}
This is invoked very simply in the html body with <form action="https://XXXXXXX.execute-api.eu-central-1.amazonaws.com/beta" method="POST">
Now, when I try to use the custom stripe checkout code, I get:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
My javascript code is:
var handler = StripeCheckout.configure({
key: '*****PRIVATE KEY*****',
image: 'logo.png',
locale: 'auto',
token: function(token) {
var xhr = new XMLHttpRequest();
xhr.open("POST","https://XXXXXXX.execute-api.eu-central-1.amazonaws.com/beta", true);
xhr.setRequestHeader('Content-Type','application/json');
xhr.setRequestHeader('Access-Control-Allow-Origin','*');
xhr.onreadystatechange = handler;
xhr.send(JSON.stringify({
body : token
}));
}
});
I have set up OPTIONS in Amazon's API Gateway to respond and have enabled CORS on amazon API gateway.
How can I pass the pre-flight request and let lambda execute the function?
Aside from enabling CORS on the API Gateway Console, your Lambda function itself has to return those CORS headers.
return {
"statusCode": 302,
"headers": {
"Location": "https://example.com/#success",
"Access-Control-Allow-Origin": "*",
}
}

CORS header ‘Access-Control-Allow-Origin’ missing Laravel 5.4

I have a problem with CORS using javascript.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://openexchangerates.org/latest.json.
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
To fix this issue I install laravel-cors package
But it didn't help at all. Can some one advice me how to fix this problem? How can I debug it to see where is the problem and why this package not working?
This is my code.
In \Http\Kernel.php
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\Barryvdh\Cors\HandleCors::class,
];
In \config\app.php
'providers' => [
Barryvdh\Cors\ServiceProvider::class,
],
In \config\cors.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Laravel CORS
|--------------------------------------------------------------------------
|
| allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
| to accept any value.
|
*/
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['*'],
'allowedMethods' => ['*'],
'exposedHeaders' => [],
'maxAge' => 0,
];
End my js:
$(document).ready(function(){
fx.base = "EUR";
fx.settings = {
from : "EUR"
};
var amount = 9.99; //in SolidShops, you could use: {{ product.price }}
// Load exchange rates data via the cross-domain/AJAX proxy:
$.getJSON(
'http://openexchangerates.org/latest.json',
function(data) {
// Check money.js has finished loading:
if ( typeof fx !== "undefined" && fx.rates ) {
fx.rates = data.rates;
fx.base = data.base;
} else {
// If not, apply to fxSetup global:
var fxSetup = {
rates : data.rates,
base : data.base
}
}
// now that we have exchange rates, add a few to our page
var USD = fx.convert(amount, {to: "USD"}); //13.22784197768393
var GBP = fx.convert(amount, {to: "GBP"}); //8.567532636985659
var JPY = fx.convert(amount, {to: "JPY"}); //1028.1670562349989
// we can now use the accounting.js library to format the numbers properly
USD = accounting.formatMoney(USD, "$ ", 2, ",", ".");
GBP = accounting.formatMoney(GBP, "£ ", 2, ",", ".");
JPY = accounting.formatMoney(JPY, "¥ ", 2, ",", ".");
$("ul.currencies").append("<li>USD estimate: " + USD + "</li>");
$("ul.currencies").append("<li>GBP estimate: " + GBP + "</li>");
$("ul.currencies").append("<li>JPY estimate: " + JPY + "</li>");
}
);
});
You need to instead use the URL https://openexchangerates.org/api/latest.json
The error message cited in the question indicates that the openexchangerates.org server isn’t sending the Access-Control-Allow-Origin response header back to your code when your code makes a request to the URL http://openexchangerates.org/latest.json.
So it doesn’t matter what CORS config you do on your own server backend where your own code is being served from. The problem you ran into was only because of the openexchangerates.org not sending back that Access-Control-Allow-Origin response header.
But if you instead use the right URL—https://openexchangerates.org/api/latest.json—then that server will send back the Access-Control-Allow-Origin header in its response, and you won’t get that “CORS header ‘Access-Control-Allow-Origin' missing” error message any longer.

extjs file uploads through form submit for cross domain

I would like to upload files to cross domain server from extjs using form.submit() method. When i call form.submit(), request is going to my restful web service and file is getting uploaded successfully. But the response is blocked at the browser with message: Blocked a frame with origi…host:1841" from accessing a cross-origin frame.
From older posts and form submit code, i found that doSubmit() is sending the Ajax request with out cors:true statement due to which cross domain response is blocked.
I thought of sending normal Ajax request but dont know how the file data can be read and send to server through ajax request.
Is there anyway in php to send the file data to server as form.doSubmit()does? Can someone help me on this problem?
Thanks.
Solution is: What does document.domain = document.domain do? and http://codeengine.org/extjs-fileuplaod-cross-origin-frame/
In case someone faces the same issue... Extjs 6.6
Objective: Using fileUpload and form.submit with CORS.
Issue: ExtJS form.submit failed due to “accessing a cross-origin frame -> The file gets successfully uploaded however it ALWAYS returns FAILURE on form.submit Reason..."Blocked a frame with origin "http://localhost:57007" from accessing a cross-origin frame."
Solution: Don't use form.submit, use fetch instead.
View
{
xtype: 'form',
reference: 'fileForm',
items: [
{
xtype: 'fileuploadfield',
buttonOnly: true,
name: 'file',
buttonConfig: {
text: 'Attach',
iconCls: 'x-fa fa-plus green',
ui: 'default-toolbar-small'
},
width: 80,
listeners: {
change: 'onAttachFile'
}
}
]
},
View Controller
/**
*
*/
onAttachFile: function (cmp, newValue) {
const self = this;
const fileForm = self.lookupReference('fileForm');
if (Ext.isEmpty(newValue) === false && fileForm.isValid()) {
const file = cmp.fileInputEl.dom.files[0];
const fileSizeInMB = parseFloat((file.size / (1024*1024)).toFixed(2));
// Validating file size
if (fileSizeInMB > 4)
alert('File size exceeds the allowable limit: 4MB');
else {
const url = '' // URL goes here
const headers = {} // Any special headers that you may need, ie auth headers
const formData = new FormData();
formData.append('file', file);
fetch(url, {
method: 'POST',
headers,
credentials: 'include',
body: formData
})
.then(response => {
response.json().then(json => {
if (response.ok) {
console.log(json);
}
else {
console.error(json);
}
});
})
.catch((error) => {
console.error(error);
});
}
}
},
Related Posts:
cross origin problems with extjs 6.01
extjs form.submit failed due to "accessing a cross-origin frame"
extjs file uploads through form submit for cross domain
ExtJS 6.6.0 Enable CORS in form submit
https://forum.sencha.com/forum/showthread.php?368824-extjs-form-submit-failed-due-to-%E2%80%9Caccessing-a-cross-origin-frame%E2%80%9D
https://forum.sencha.com/forum/showthread.php?298504-Extjs-5-Fileupload-submit-error
https://forum.sencha.com/forum/showthread.php?294852
https://forum.sencha.com/forum/showthread.php?343448-Cross-origin-file-upload
Ajax call does not work with downloading and i presume with uploading files.
Have you tried to set this before doSubmit:
Ext.Ajax.cors = true;
Ext.Ajax.useDefaultXhrHeader = false;
Solution is: What does document.domain = document.domain do? and http://codeengine.org/extjs-fileuplaod-cross-origin-frame/

Categories

Resources