GET lambda function using postman (authorization header) - aws-lambda

I'm trying to do simple GET lambda function via postman using API gateway.I'm getting 200 OK using authorization code in lambda function but
I want to pass authorization token when calling from postman
exports.handler = async(event) => {
try {
const res = await axios.get('https://hellothere.com/1435',{
headers : {
'Authorization': 'Bearer XXXXXXX',
'Content-Type' : 'application/json'
}
})
console.log(res)
return {
statusCode: 200,
body: JSON.stringify(res.data)
}
} catch (e) {
console.log(e)
return {
statusCode: 400,
body: JSON.stringify(e)
}
}
};
I don't want to give Authorization token in the code instead when I can call from postman I want to pass the token

Related

Is there a way to return JSON on ALB lambda?

I have created lambda function on node.js which returns JSON.
It connected with API Gateway and worked well.
I want to connect it to amazon load balancer.
I tried it but it returns HTML page.
async function run(event)
{
let ret = {};
ret = {
'statusCode': 200,
'statusDescription': '200 OK',
'headers': {
'Content-Type': 'application/json'
}
}
ret.code = 200;
return ret;
}
exports.handler = run;
How to return JSON?
Add a stringified body attribute to the response
async function run(event)
{
let ret = {};
ret = {
'statusCode': 200,
'statusDescription': '200 OK',
'headers': {
'Content-Type': 'application/json'
},
'body': JSON.stringify({
test: 1
})
}
ret.code = 200;
return ret;
}
exports.handler = run;

Error during upload image to imgur - inavlid URL

i have some troubles with imgur api. I converted image to base64 code and tried upload it to imgur api. Unfortuatelly I'm receiving an error:
"error": "Invalid URL (data:image/png;base64,iVBORw0KGgoAA..."
Here's my function:
uploadImageToImgur: function (file) {
const url = 'https://api.imgur.com/3/image',
reader = new FileReader();
reader.onloadend = async function () {
let { result } = reader;
try {
const request = await fetch(url, {
method: 'POST',
headers: {
"Authorization": 'my client key',
},
body: result
});
const response = await request.json();
console.log(response);
} catch (e) {
throw new Error(e);
}
}
if (file) {
reader.readAsDataURL(file);
}
}
You need to cut this part out.
You are missing some parameters. Also, make sure your headers have the Client-ID key.
const request = await fetch(url, {
method: 'POST',
headers: {
"Authorization": 'Client-ID {yourKey}',
},
form: {
"image": result,
"type": "base64"
}
});

Netlify Lambda Functions

I am having an issue getting a 502 error back when I call my Netlify function. Is there something I am doing wrong in my Axios call or does the "error" sent in the callback need to be an actual Error object?
Below is the example of my function:
const axios = require('axios')
require('dotenv').config()
const https = require('https')
const headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type'
}
exports.handler = function (event, context, callback) {
// your server-side functionality
axios
.post(
`https://us18.api.mailchimp.com/3.0/lists/${
process.env.LIST_ID
}/members/`, {
email_address: 'deuce3608#gmail.com',
status: 'subscribed'
}, {
auth: {
username: 'admin',
password: process.env.MAILCHIMP_API_KEY
}
}
)
.then(response => {
callback(null, {
statusCode: 200,
headers,
body: response.data
})
})
.catch(err => {
callback(JSON.stringify(err.response.data))
})
}
Netlify announced in April (2018) that Node.js 8.10 would be the default in Netlify functions.
Using Callback Parameter:
When you need to return an error in Lambda functions on Netlify using the Callback Parameter, it will be the same format as the Lambda functions for AWS.
You will need to return an Error in the first parameter of the callback as you can see in the AWS documentation
callback(Error error, Object result);
The error is used if not null and the result will be ignored.
Using Async Handler:
You also have the option to return your error in the response with an error status code like the example function below.
import fetch from "node-fetch";
const API_ENDPOINT =
"https://08ad1pao69.execute-api.us-east-1.amazonaws.com/dev/random_joke";
exports.handler = async (event, context) => {
return fetch(API_ENDPOINT)
.then(response => response.json())
.then(data => ({
statusCode: 200,
body: `${data.setup} ${data.punchline} *BA DUM TSSS*`
}))
.catch(error => ({ statusCode: 422, body: String(error) }));
};
Showing simple tests
Error
exports.handler = function(event, context, callback) {
const err = new Error("this is an error")
callback(err);
}
Response (response status code 502):
{"errorMessage":"this is an error","errorType":"Error","stackTrace":["48.exports.handler (/var/task/showerror.js:75:13)"]}
Object
exports.handler = function(event, context, callback) {
const err = {statusCode: 422, body: "this is an error"}
callback(err);
}
Response (response status code 502):
{"errorMessage":"[object Object]"}
String
exports.handler = function(event, context, callback) {
const err = "this is an error"
callback(err);
}
Response (response status code 502):
{"errorMessage":"this is an error"}
NOTE:
If you want to use callback and have the error status code in the response, you would just pass it in an object to the response.
exports.handler = function(event, context, callback) {
const err = {statusCode: 422, body: "this is an error"}
callback(null, err);
}
Response (response status code 422):
this is an error
You could arrange the response like so:
var response = {
statusCode: 4xx
body: ''
}
and then pass it to the callback to return the error
response.body = 'some error text here';
callback(response);
They are using AWS Lambda, so if you can do it in the console you should in theory be able to call things the same way since they are taking your code and deploying it via Cloudformation in their infrastructure.

react-native fetch with authorization header sometime return 401

I'm facing some issue whereby I sometime will get status code 401 (Unauthorised) from my phone. I'm trying to access to an API from my computer localhost (192.168.0.7).
I've a screen, when I click on a button it will navigate to a page and it will request data through API. And when I go back and navigate to same page again, it sometime will return me code 401.
So if I repeat the same step (navigate and go back) let's say 10 times. I'm getting Unauthorised like 5-7 times.
Below are my code
export function getMyCarpool(param,token) {
return dispatch => {
var requestUrl = _api + 'GetMyProduct?' + param;
fetch(requestUrl, {
method: "get",
headers: new Headers({
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + token
})
})
.then((request) => {
console.log(request);
if(request.status == 200)
return request.json();
else if(request.status == 401) {
//dispatch(logout());
throw new Error('Unauthorized access.');
}
else
throw new Error('Failed to request, please try again.');
})
.then((response) => {
var message = response.message;
if(response.success == 'true')
dispatch({ message, type: GET_MY_PRODUCT_SUCCESS });
else
dispatch({ message, type: GET_MY_PRODUCT_FAILED });
})
.catch(error => {
var message = error.message;
dispatch({ message, type: GET_MY_PRODUCT_FAILED });
});
}
I've check the token in my phone and also trying to make many request using postman. So I don't think it's server side problem.
I'm using Laravel and using laravel passport for API authentication. I not sure why this happen if I continue to access many time, any help is greatly appreciated.
UPDATE :: I'm trying to capture whether the http request has the token from this link, and I don't get the problem anymore.
It's a healthy mechanism for token expire. Maybe you have your token (access_token) for 5 minutes, then the token expired, you should use refresh_token to regain another new token (access_token).
For code explanation:
async function fetchService(url) {
const reqSetting = {
headers: {
Accept: 'application/json',
Authorization: `Bearer ${Auth.access_token}`,
},
};
const prevRequest = { url, reqSetting };
const resp = await fetch(url, reqSetting);
if (!resp.ok) {
const error = new Error(resp.statusText || 'Request Failed!');
if (resp.status === 401 || resp.status === 400) {
const responseClone = resp.clone();
const errorInfo = await resp.json();
if (errorInfo.error == 'invalid_token') {
// console.log('Token Expired', errorInfo);
try {
await refreshToken();
const response = await fetchService(prevRequest.url);
return response;
} catch (err) {
// handle why not refresh a new token
}
}
return responseClone;
}
error.errorUrl = url;
error.code = resp.status;
throw error;
}
return resp;
}
Where the refresh token function is :
async function refreshToken() {
const url = 'https://example.com/oauth/token';
const data = {
grant_type: 'refresh_token',
refresh_token: Auth.refresh_token,
};
try {
const res = await fetch(url, data);
const data = res.json();
Auth.access_token = data.access_token;
Auth.refresh_token = data.refresh_token;
return true;
} catch (error) {
throw error;
}
}
This fetchService will automatic regain a new token if old expired and then handle old request.
PS.
If you have multiple requests same time, the fetchService will need a little optimization. You'd better choose another regain token strategy like saga.

BadArgument and JSON parsing error when making an API call

Inside my component, I'm trying to make an api call using fetch.
The API takes in an image .jpg file path as such - file:///var/mobile/Containers/Data/Application/1E1E919E-6C21-4CC7-B9C2-5B4B3BC84B0F/Library/Caches/ExponentExperienceData/%2540chuks93%252Fihu-main/Camera/F3B8EBCC-BB09-4603-AF7E-FD3CA792C237.jpg and it should return a JSON object.
Here's my fetch call below:
export default {
processImage: (image) => {
// Replace the subscriptionKey string value with your valid subscription key.
var subscriptionKey = "*******************";
var uriBase = "https://westus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise";
// Display the image.
var sourceImageUrl = image;
console.log(typeof sourceImageUrl)
console.log("here", sourceImageUrl);
// Perform the REST API call.
return fetch(uriBase, {
method: 'POST',
headers: {
"Content-type": "application/json",
"Ocp-Apim-Subscription-Key": subscriptionKey
},
body: JSON.stringify(sourceImageUrl),
})
.then((data) => data.json())
.then(function (data){
console.log("hello", data);
})
.catch(function (error) {
console.log(error);
});
}
}
When I run the above code this is the error it returns:
Object {
"error": Object {
"code": "BadArgument",
"message": "JSON parsing error.",
}
Any thoughts on this?
Change your
body: JSON.stringify(sourceImageUrl),
to
body: JSON.stringify({url: sourceImageUrl}),
to make the body of the post a proper json object.

Resources