Can't POST item to my DynamoDB table with axios - javascript

I’m trying to POST an item in VS Code to my DynamoDB table via axios. I’m able to POST an item successfully via Postman, however when I try to POST an item with axios I get a 404 response error (below).
I’m wondering if I’m missing something when trying to POST an item via axios (below).
axios({
'method': 'post',
'url': 'https://na9blqj5y5.execute-api.us-east-1.amazonaws.com/test',
'Content-Type': 'application/json',
'data': {
'body': eraseThis,
}
})
.then((response) => {
return console.log('axiosResp', response);
})
.catch((err) => console.error('axios', err))
One thought that I had is that I should be importing the AWS SDK and invoke my lambda function with my credentials from that (below)? Any help would be greatly appreciated!
This is a successful POST request in Postman.
Now I'm getting a CORS error I had a few weeks ago (even after enabling CORS on the API resource in the API Gateway interface).
Below is the updated code using the aws-sdk

Your examples are hard to follow because they don't match.
first screenshot url is a different api gateway endpoint address than the postman screenshot
first uses the /test stage and the 2nd uses a /prod/customer
So right off I'm wondering if you just have different code deployed to different stages? Assuming you've ruled that out though and that's not the case I think what you mean to say is that your axios call made via browser fails whereas postman works.
That's actually expected behavior because postman isn't a browser and bypasses the CORS restrictions that browsers implement. There are plenty of existing questions here that explain that so I'm not going into that further.
I believe the fix for this is to update your lambda handler (the actual lambda proxy that returns a response) to always return a Access-Control-Allow-Origin header as documented by AWS here. To allow all origins you can use a wildcard *. ex:
headers: {
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET"
}
Make sure you understand the implications of using *, which is a discussion for a different post.

Not sure what I did, but the call to dynamodb randomly started working. I think I had a syntax error, or something..

Related

Check if Youtube thumbnail exists using JavaScript fetch

I know questions like that have been asked tons of times already but I still was not able to find a solution or even an explanation for that manner.
I work on a project that needs the best possible resolution on YouTube thumbnails. I used the following url https://i.ytimg.com/vi/VIDEOID/maxresdefault.jpg however I found out that on rare occasions this does not work and I get a placeholder image, and a status of 404, back. In that case I would like to use https://i.ytimg.com/vi/VIDEOID/hqdefault.jpg.
To check if an image exists I tried to make a fetch-request using JavaScript:
const url = "https://i.ytimg.com/vi/VIDEOID/hqdefault.jpg"
fetch(url).then(res => console.log(res.status))
But I get an error stating that the CORS-Header 'Access-Control-Allow-Origin' is missing. I tried setting it and several other headers I found but to no avail. It only works if I send the request in no-cors mode, but then the status is always 0 and all the other data seems to be missing aswell.
I also tested the request in Postman where it worked and even copied the JavaScript-Fetch-Snipped that Postman gave me:
var requestOptions = {
method: 'GET',
redirect: 'follow'
};
fetch("https://i.ytimg.com/vi/VIDEOID/maxresdefault.jpg", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
I read that this is a problem from the Server and Youtube is restricting this, but why does it work in Postman and why does it work when using <cfhttp> in ColdFusion? Also the status-code even shows up in the console within the CORS-Error message...
Why? explained:
The CORS policy is implemented in browsers to allow sharing resources between websites while preventing websites from attacking each other:
SOP (same origin policy) prevents web sites from attacking each other but does not allow any sharing between origins.
CORS (cross origin resource sharing) relaxes SOP restrictions, but requires specific server headers/configuration.
These policies only apply inside a browser. Presumably Postman and Coldfusion work because they are making direct HTTP requests outside the context of a browser script. Which leads to how to work-around CORS restrictions...
Solutions:
3 Ways to Fix the CORS Error — and How the Access-Control-Allow-Origin Header Works explains how to bypass CORS restrictions. They all work by manipulating the request headers/origin:
Browser extension. (Not sure if this still works in 2022. Only works if user installs browser extension.)
3rd party request proxy. (The proxy linked in the demo is now limited due to abuse.)
Build your own proxy.
Realistically, option #3 is the only real solution. SvelteKit endpoints make it super simple to proxy requests.
Following code is working properly for me and I am always getting 200 status ok
Something similar implementation can be done
//import fetch from 'node-fetch';
const fetch = require('node-fetch');
loaddata();
async function loaddata(){
var Headers="{headers: {'Access-Control-Allow-Origin': '*'}";
var requestOptions = {
method: 'GET',
redirect: 'follow',
};
const response = await fetch('https://i.ytimg.com/vi/9DCwyuH29SI/hqdefault.jpg',requestOptions,Headers);
console.log(response);
}

Making Get request to Yammer API works using Postman tool but not with Vue-Resource

I am trying to integrate Yammer API in my Vue.JS project, for Http calls I am using Vue-Resource plugin. While making GET Http call to get posts from Yammer it gives me following error -
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
I tried postman tool and that gives successful response, but when I try to run the same thing in my Vue.JS project using Vue-Resource plugin it wont work.
The Vue.JS code snippet -
function(){
this.$http.get("https://www.yammer.com/api/v1/messages/my_feed.json").then((data)=>{
console.log(data);
});
In main.vue file i have -
Vue.http.interceptors.push((request, next) => {
request.headers.set('Authorization', 'Bearer my_yammer_token')
request.headers.set('Accept', '*/*')
next()
})
Then I tried the code snippets provided by Postman tool for jquery, that too not working.
jQuery code -
var settings = {
"url": "https://www.yammer.com/api/v1/messages/my_feed.json",
"method": "GET",
"timeout": 0,
"headers": {
"Authorization": "Bearer my_yammer_token",
"Cookie": "yamtrak_id=some_token; _session=some_token"
},
};
$.ajax(settings).done(function (response) {
console.log(response);
});
Though, I found similar questions but nothing worked for me.
I am working this to resolve from last 2 days but getting failed again and again. Please guide/help me.
A browser has higher security requirements than a request in PostMan. In a browser, you are only allowed to make XHR requests to your own current host (combination of domain + port) but not to other remote hosts. To nevertheless make a request to a remote host, you can use the browser built-in CORS. By using this, your browser makes a pre-flight request to the remote host to ask if the current page is allowed to request from that host. This is done via the Access-Control response headers. In your case, this header is probably missing or not allowing your page to access, which is why the request does not go through. Please read further into that topic.
However, in your case, using CORS probably won't be a solution for two reasons: To use CORS, the remote host must present a header which allows every requesting host (*) or your specific one. If you cannot set that setting anywhere on the remote host, it won't work. Second, it is not safe to place your authorization token into client-side JavaScript code. Everybody can just read your JS code and extract the authorization token. For that reason, you usually make the actual API call from the server-side and then pass the data to the client. You can use your own authentication/authorization against your server and then use the static authorization key on the server to request the data from the remote host. In that case, you'll never expose the authorization key to your user. Also, on the server-side, you do not have to deal with CORS as it works just like PostMan or curl as opposed to a browser.

Chrome CORB blocking APIGateway lambda request

What works
I have a simple word game I've built. It works great. One thing users have requested is a word validity check. I am running the oxford dictionary api on an AWS Lambda Proxy/Node.js end-point, which works great when I access the APIGateway uri via the browser.
I chose an AWS Lambda function in order to protect my Oxford API key, and have more direct CORS control.
Steps taken
I have enabled CORS in the AWS APIGateway, and using a "*" wildcard during development.
I started to code the addition to the game, using my local server, # 127.0.0.1.
Error encountered
I have run into the following issue:
myproject.html:57 Cross-Origin Read Blocking (CORB) blocked cross-origin response https://XXXXXXXXXXX.execute-api.us-east-2.amazonaws.com/prod/dictionary?word=help with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.
getWord # myproject.html:57
(anonymous) # myproject.html:67
The client code
I am using a simple fetch:
var base_url = "https://XXXXXXXXXXX.execute-api.us-east-2.amazonaws.com/prod/dictionary?word=";
getWord = function(word){
fetch(base_url+word, {
headers: {
'content-type': 'application/json'
},
method: 'GET',
mode: 'cors'
}).then(function(response) {
console.log(response);
});
}
The question
I have never heard of CORB. I don't understand what is triggering CORB, and what the steps are to resolve this. How are CORB issues resolved?
I just needed to persevere apparently. Just in case anyone ever runs into this:
Despite APIGateway CORS enablement, CORS authority is passed to the lambda function with Lambda proxy integration enabled. Although the initial URI request was accepted at the APIgateway, it ultimately failed due to lack of headers in the lambda response. Somehow This triggered CORB instead of CORS. I don't know why.
The answer is to ensure CORS is enabled in the APIgateway and that the lambda function response callback pattern contains a "Access-Control-Allow-Origin" header.
I had similar issue. I suggest using POSTMAN for debugging it as it shows headers and allows you to tweak whatever is needed in your request.
In my case I had to re-deploy my API after adding the header.
Attaching screenshot in case it might be of help to some users:
Integration response:
Method response:
Postman's headers response - working:

Header not coming to service while Get Request is made from Angular

I have an angular JS application, from where I am calling a GET API. The API is OAuth 2.0 enabled, so requires a Bearer Token in the header. So, I am calling the http method like this:
var config = {
headers: {
'Access-Control-Allow-Origin': '*',
'Authorization': "Bearer XXXXXXX"
}
};
$http.get("http://host:port/api_call", config)
.then(function (response) {
return response.data;
});
But when I am making this call, I am getting 401 Unauthorized exception. Initially I thought of this as a CORS issue, So I whitelisted the origin to make call to the services host, but still didn't work. So, I checked the logs and found that Authorization header is not coming to the API application, though angular is sending the same.
Note: Is this the best way to make a service call from Angular?
I am quite new to Angular JS and thus have almost no idea how to diagnose or troubleshoot this type of issues. Can someone please tell me the possible errors/how to troubleshoot this?
The issue was in the API gateway. It was not able to make Cross Origin Calls and thus the API call was terminated there, hence Authorization header was not coming.

Preflight OPTIONS request returns status 405

I am currently developing a dashboard which consumes the Mention API. However, I am having difficulties due to the CORS policy.
If the dashboard is opened on Chrome or another browser that has a strict CORS policy, they make a preflight OPTIONS request each time, but these appear to not be supported by the Mention API.
Therefore, every time I do something like:
this.mentionAPI = axios.create({
baseURL: 'https://web.mention.net/api/accounts/my-account-id',
headers: {
'Authorization': 'Bearer my-access-token',
}
});
this.mentionAPI.get('/alerts')
.then((response) => {
console.log(response);
})
.catch((response) => {
console.log(response);
});
I get a response with the status 405 Method Not Allowed. This suggests that the OPTIONS requests are not handled by the Mention API at all.
Naturally, in my case I can just make sure that the browser is configured to not perform preflight requests. After all, my use case prescribes just one client, which I control completely. Alternatively, I could build a server-side service to make the requests on my behalf, however it seems like hunting a fly with cannon, since client side JavaScript is more than capable to perform everything else.
Any help on this issue would be really appreciated. Perhaps I'm misunderstanding how the API is intended to be consumed?

Categories