Serverless CORS preflight request failed - AWS API Stripe - javascript

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": "*",
}
}

Related

JSON post request shows 405 not allowed error (using XMLHttpRequest())

here's my js code:
var myreq=new XMLHttpRequest();
myreq.open("GET","https://<username>.github.io/test/data/data.json",true);
myreq.onload =function(){
console.log(JSON.parse(myreq.response));
}
myreq.send();
const data={
"name": "jayant",
"job": "leader"
};
function here()
{
var myreq1=new XMLHttpRequest();
myreq1.onload = () => {
// print JSON response
if (myreq1.status >= 200 && myreq1.status < 300) {
// parse JSON
const response = JSON.parse(myreq1.responseText);
console.log(response);
}
};
myreq1.open("POST",'https://<username>.github.io/test/data/data.json');
myreq1.setRequestHeader('Content-Type', 'application/json');
myreq1.send(JSON.stringify(data));
}
Function here is called on a button click
and here's my JSON code:
[
{
"name1":"jayant",
"age":58,
"pass":"LetsLearnJson"
},
{
"name1":"jayant2",
"age":45,
"pass":"ok"
},
{
"name1":"jayant3",
"age":24,
"pass":"test"
},
{
"name1":"abcd",
"age":75,
"pass":"abcd"
}
]
I am getting this error when I try to post:
POST https://<username>.github.io/test/%22https://<username>.github.io/test/data/data.json%22 405
Please help. I have tried many things already available online but nothing seems to work
The 405 Method Not Allowed Error occurs when the web server is configured so that you cannot perform a specific action for a specific URL. It is an HTTP response status code that indicates that the request method is known to the server, but is not supported by the target resource.

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.

Access-Control-Allow-Credentials' header in the response is "" which must be 'true'

I'm trying to send a comment to a REST api. That rest API has the CORS already set for my app address..
BackEnd
#RestController
#CrossOrigin(origins = "http://localhost:8000", allowedHeaders = "*", methods = {RequestMethod.GET,RequestMethod.POST,RequestMethod.DELETE,RequestMethod.PUT})
#RequestMapping("/api")
public class CommentController {
#Autowired
private CommentRepository commentRepository;
// Get All Comments From a certain workitemId
#GetMapping("/comments/{workitemId}")
public List<Comment> getTicketHistory(#PathVariable Long workitemId) {
return commentRepository.getCommentsByWorkitemId(workitemId);
}
// Create a comment related with a given Workitem
#PostMapping("/comment")
public boolean createComment(#RequestBody Comment comment) {
commentRepository.save(comment);
return true;
}
}
But I get
Failed to load http://localhost:8999/api/comment: Response to
preflight request doesn't pass access control check: The value of the
'Access-Control-Allow-Credentials' header in the response is '' which
must be 'true' when the request's credentials mode is 'include'.
Origin 'http://localhost:8000' is therefore not allowed access. The
credentials mode of requests initiated by the XMLHttpRequest is
controlled by the withCredentials attribute.
My Code:
$http.post(baseUrl + "/comment", vm.comment).then(
function(response) {
// success callback
console.log("Comment Submitted!");
},
function(response) {
// failure call back
console.log("Error while submitting the comment");
});
Try adding allowCredentials = "true" in #CrossOrigin annotation as,
#CrossOrigin(
allowCredentials = "true",
origins = "http://localhost:8000",
allowedHeaders = "*",
methods = {RequestMethod.GET,RequestMethod.POST,RequestMethod.DELETE,RequestMethod.PUT}
)
This might work.
You forgot to add:
allowCredentials=true
It shoul be:
#CrossOrigin(origins = "http://localhost:8000", allowCredentials = "true", allowedHeaders = "*", methods = {RequestMethod.GET,RequestMethod.POST,RequestMethod.DELETE,RequestMethod.PUT})

Angular fetch vine thumbnail

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

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