I get
While attempting to enable CORS on API Gateway, why is that and how do I resolve this? These functions are deployed using AWS SAM. But I notice if I create my own APIs via AWS Console this happens too
The errors looks like:
invalid model name specified application/json=Empty
invalid response status code specified
I found I seem to need to add an "Empty" response model myself?
Now, I get
Add Access-Control-Allow-Origin Integration Response Header Mapping to POST method (invalid response status code specified)
How do I resolve this?
Firstly please select your root resource and select "Enable CORS". It will enable CORS to all methods. Ideally it should work. If in case it doesn't work Please add an empty json in the response as I have marked in the screenshot attached. I believe you don't have any default response header added in your OPTIONS method response (in Method Response ). Please refer screenshot
Create a new model from the left menu that you will call Empty and it works
I had a CORS problem with API Gateway + Lambda and the above answers did not help me but I figured out I needed to add some headers information to my response code in my API.
I needed to add the res.statusCodeand the two headers.
// GET
// get all myModel
app.get('/models/', (req, res) => {
const query = 'SELECT * FROM MyTable'
pool.query(query, (err, results, fields) => {
//...
const models = [...results]
const response = {
data: models,
message: 'All models successfully retrieved.',
}
//****** needed to add the next 3 lines
res.statusCode = 200;
res.setHeader('content-type', 'application/json');
res.setHeader('Access-Control-Allow-Origin', '*');
res.send(response)
})
})
2020 answer: Nowadays, there's an option called HTTP API when creating an API in the dashboard. For this type, I've found the CORS configuration to be much easier. If you have a working API of this type, you just have to click "CORS" under "Develop" in the sidebar, and then add '*' under Access-Control-Allow-Origin.
Related
I am trying to fetch data from a JSON file through NextJS internal API on the client side. But it is always throwing 503 error:
The Lambda function associated with the CloudFront distribution is invalid or doesn't have the required permissions.
We can't connect to the server for this app or website at this time. There might be too much traffic or a configuration error. Try again later, or contact the app or website owner.
I tried to use the GET method with query params in the URL, but it didn't work, then I try the POST method with the query in the body(just to test out), but it also didn't work either.
Here is the code:
const response = await fetch(`/api/search?q=${query}`, {
method: "GET",
headers: {
'Content-Type': 'application/json',
},
})
const res = await response.json()
I have another component that sends some user inputs to save in my DB, and it is working perfectly. (I am really confused why one works but not other given both are equivalent request)
Also, the same app deployed on Vercel is working perfectly. So I think the issue is with Amplify.
Anyone had similar issues with the Next app on Amplify? please help.
most likely you are sending a GET request but you have something in the body. e.g. form-data. this is example in postman.
I have a site on AWS Amplify that is making an API call to an API Gateway Lambda integration. After strugglebussing with CORS errors for quite a while, I got it working but my headers arent what I expect.
Below is my API gatweway config: I have two allow-origin values and only GET, POST, OPTIONS methods being allowed.
After applying these settings, when I look in the browser f12 network panel when running these API calls through the website, I see that the access-control-allow-headers, access-control-allow-methods, and access-control-allow-origin are set to values that I have not assigned in my config:
So on to the question - Are the response header results normal? I expected to see the headers and http methods I allowed/exposed in the browser api calls and I'm seeing completely different values. I dont know if this is normal.
Thank you!
check your code if you are not exposing all methods in CORS. e.g. if it is on node js / express then below snippet can cause that problem. you can always limit those controls here. If I'm not wrong then your code overrides your gateway configurations.
// Enable CORS for all methods
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "*");
next();
});
I get the following error message when calling actions for CloudWatch in API Gateway.
"Error": {
"Code": "InvalidAction",
"Message": "Could not find operation DescribeAlarms for version 2009-05-15",
"Type": "Sender"
}
I've been using DescribeAlarms for testing. My setup is as follows.
Integration Type = AWS Service
AWS Service = CloudWatch
HTTP method = POST
Action = DescribeAlarms
The error references the API Version 2009-05-15, which only has ListMetrics and GetMetricStatistics according to it's documentation on page 54. ListMetrics does indeed work as expected with my setup.
The current version is 2010-08-01 but I don't see anyway to reference that in API Gateway. In an example of a POST request in the documentation it shows a header labeled x-amz-target with a value of GraniteServiceVersion20100801.API_Name.
My interpretation is I can put Name = x-amz-target and value 'GraniteServiceVersion20100801.DescribeAlarms' in my http header for the Integration Request in API Gateway.
This doesn't change the response and gives the same error message.
I also used the --debug in CLI when calling describe-alarms, and in the body it shows...
"body": {
"Action":"DescribeAlarms",
"Version":"2010-08-01"
}
So I also set http headers to include Content-Type with a value of 'application/x-amz-json-1.1' and then put in
{
"Action":"DescribeAlarms",
"Version":"2010-08-01"
}
but nothing changed with that either.
Any help or guidance would be greatly appreciated.
Under Method Integration -> URL Query String Parameters
I added Version as the Name and '2010-08-01' under Mapped From.
All actions are now working as expected.
I'm trying to PutMetrics directly from Api Gateway -> Cloudwatch using PutMetricData, Version in the query string params didn't work for me.
These 3 HTTP headers in the Integration Request solved it for me:
Content-Type 'application/json'
X-Amz-Target 'GraniteServiceVersion20100801.PutMetricData'
Content-Encoding 'amz-1.0'
I'm almost complete with a new web app, however, I'm getting a 403 error from AWS's API Gateway due to a CORs issue.
I'm creating a Vue app and using Vue's axios library. CORs is enabled and the request works with API Key Required option turned off in AWS's API Gateway by sending the following:
axios
.get('My-URL-Endpoint',{headers: {})
.then(response => (this.passports = response.data ));
When I turn on API Key Required functionality inside AWS's API Gateway. It works when I use Postman along with including x-api-key: My-API-Key. However, using Vue's axios it does not work and returns error 403:
axios
.get('My-URL-Endpoint', {headers: {
'x-api-key': 'My-API-Key'
}})
.then(response => (this.passports = response.data ));
My first instinct is that the problem is related to how Axios is sending the request through the browser. From what I can gather it looks like the pre-flight check is failing because I am receiving the following error within the browser:
Access to XMLHttpRequest at 'My-URL' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Sure enough it looks like there is no access-control-allow-origin key in the response. So I added access-control-allow-origin to the response of the 403 message and got a new error "It does not have HTTP ok status"
I've been trying nearly everything to get this to work! I came across stackoverflow answer where it seems like the person was suggesting that API Key Required Key functionality can't work with CORs. This kind of seemed like that cannot be true. It would be a pretty crippling restriction.
So my question is how to get the browser's pre-flight check to work along with CORs and API Key capability inside AWS's API Gateway?
Thank you!
If you have enabled cors on your api gateway, the next place to look is the application code such as lambda. Make sure the Lambda is returning the correct cross origin headers in both successful and failure scenarios.
First of all you can check if the request is reaching the lambda from the cloud watch logs. Another way to check this is to temporarily point the Api gateway target to the Mock end point.
If the mock endpoint works, then the problem is the application code. otherwise the problem is in your api gateway end point.
Also note that any headers you use should be white listed in the Access-Control-Allow-headers section when you enable to cors for your method/resource.
I am trying to generate an embed token for a report by calling below endpoint but it thorws me CORS issue.
Failed to load
https://api.powerbi.com/myorg/groups//reports//GenerateToken:
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:4200' is therefore not allowed
access. The response had HTTP status code 403.
Is there any setting in power bi dashboard or enable CORS and set allowed origins?
you shouldn't get cors issue if you called power api in server side code.
No setting changes required in powerbi dashboard.
Please share code snippet if you can.
CORS is a browser security feature that disallows cross site referencing. Hence there isn't any setting on the PowerBI part to get it fixed. We earlier worked with the REST APIs but faced CORS issue on almost every browser. Using the CORS plugin for Chrome fixed the issue. But can't expect every user to install the client side plugin.
As a work around, we took the WebAPI approach, wherein our client side script hit the WebAPI endpoint, communicated with the PowerBI service to return the report. To overcome the CORS issue this way, add a reference to System.Web.Cors in the WebConfig.cs file found under App_Start folder and add the line config.EnableCors();
In the Controller, decorate the method with EnableCors as shown below and that should resolve your problem:
namespace MyNameSpace.MyControllers
{
public class MyAPIController : ApiController
{
[HttpPOST]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public string getData()
{
return "This Works !";
}
}
}