GET image from authenticated route - node.js

I have a working image-upload front/back-end code working. Now I would like to be able to GET the image from server after it is uploaded.
The problem is that the images must be behind an authenticated route, where user has to pass jwt token in header or body.
When i try to fetch the image like this:
fetch(imageURL, {
method: 'GET',
headers: {
'x-access-token': localStorage.getItem('token')
}
I just get a Form object as the response:
<img alt="Your pic" src="[object FormData]">
Would there be some way to get the image into HTML 'img' tag other than just pasting the url in 'src' attribute, since it leads to 401 (Unauthorized)

You can try the following snippet:
const myImage = document.querySelector('img');
// I make a wrapper snippet which will resolve to a objectURL
function fetchImage(url, headers) {
return new Promise((resolve, reject) => {
fetch(url, headers)
.then(response => response.blob()) // sending the blob response to the next then
.then(blob => {
const objectUrl = URL.createObjectURL(blob);
resolve(objectUrl);
}) // resolved the promise with the objectUrl
.catch(err => reject(err)); // if there are any errors reject them
});
}
fetchImage(imageUrl, {
method: 'GET',
headers: {
'x-access-token': localStorage.getItem('token')
}
})
.then(objectUrl => myImage.src = objectUrl)
.catch(err => console.log(err));
An other example for you to try you can find at:
https://davidwalsh.name/convert-image-data-uri-javascript

Related

forward the response of http request to the client

I am invoking a web service through an azure function in node.js with Axios, I have a couple of questions here.
1- in the body of this request I'm hardcoding the value for appUser. however, if I want to run this request on postman and pass the JSON value in the body for appUserwhat changes do I need to do in the code so the param value can pick up what is being passed.
2- the response for this request is only returned in the console of the editor but not getting sent to the client response body (i.e. postman) any idea how to forward the response?
module.exports = async function () {
const axios = require("axios");
const data = {
appUser: "yamen",
};
const headers = {
Authorization:
"Basic WUFNkVQRDg9",
};
{
axios
.post(
"https://tegossl/GetAppUser?company=Enva",
data,
{ headers: headers }
)
.then((response) => {
console.log(`Status: ${response.status}`);
console.log("data: ", response.data);
})
.catch((err) => {
console.error(err);
});
}
};

AWS-Lambda 302 Not Redirecting after getting response from Axios (Frontend)

I'm trying to setup a Google-OAuth flow using serverless and AWS-Lambdas. To start, I have a button that kicks off the process by hitting a lambda endpoint. However, the page never actually redirects to the authentication page. Instead I get an error on the FE:
Request failed with status code 302
Frontend logic:
const redirectToGoogleOAuth = async (user) => {
try {
const endpoint = process.env.GOOGLE_PATH_ENDPOINT;
const response = await axios.get(endpoint, {
responseType: 'text',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${user}`,
},
});
// Expect redirect at this point
return response.data.data;
} catch (err) {
throw new Error(err.message);
}
};
Lambda Endpoint:
module.exports = async (event, context) => {
const responseType = 'code'
const googleAuthorizeURL = 'https://accounts.google.com/o/oauth2/v2/auth'
const scope = 'openid email https://www.googleapis.com/auth/contacts.readonly'
const accessType = 'offline'
try {
const params = [
`response_type=${responseType}`,
`client_id=${googleClientId}`,
`redirect_uri=${baseURL}`,
`scope=${scope}`,
`state="state"`,
`access_type=${accessType}`
]
const googleOAuthEndPath = `${googleAuthorizeURL}?${params.join('&')}`
const response = {
statusCode: 302,
body: '',
headers: {
location: googleOAuthEndPath
}
}
return response
} catch (err) {
return response(400, err.message)
}
}
In the lambda-response, I've added a header for location with the google-path. However, the frontend does not seem to consume the response correctly. The frontend interprets the 302 as in error instead of redirecting to the specific page. Any ideas on how I may resolve this so it actually redirects?
Axios uses XHR, which always follows redirects by itself and therefore Axios can't do anything about it (unless you rely on hacks, discussed in the same link).
You might have to use something other than Axios for this part, such as the Fetch API, which supports manual redirects.
GitHub user parties suggested the fetch() equivalent in the same Axios issue linked above:
fetch("/api/user", {
redirect: "manual"
}).then((res) => {
if (res.type === "opaqueredirect") {
window.location.href = res.url;
} else {
return res;
}
}).catch(handleFetchError);

Fetch image and send it using koa2

I am trying to fetch an image from external URL and then send it as a response in koa2. For fetching the image I am using Axios library.
I am trying to do that the following way:
router.get('/get-image', async (ctx, next) => {
const {authToken} = ctx.query
const response = await axiosInstance.get(
'https://www.someurl.com/image/992',
{
headers: {
Authorization: `Bearer ${authToken}`,
},
}
)
ctx.type = 'image/jpeg'
ctx.body = response.data
})
But the image I get from that request is not valid. It only shows empty rectangle).
Can someone point me in the right direction on how to resend the received image?
Set responseType: 'stream'. 'arraybuffer' works too, but 'stream' is even better since you're just passing through the bytes.
By default, I believe axios decodes into a utf-8 string which of course is nonsensical for image binary data.
const response = await axios.get(url, {
responseType: 'stream',
...
})

Cypress : how to forward response body JSON to be used on headers

i'm gonna test REST API using Cypress.io , but using chaining request, it wants to be work like this, JSON response body on the first API will be used on the next API Headers for Authorization
I'm already try doing by using cypress commands and printing on console.log, but seems like it does not captured on the log, or is there any clue for this, or i just using another command like cy.route ?
Cypress.Commands.add("session", () => {
return cy.request({
method: 'POST',
url: '/auth/',
headers: {
'Content-Type': 'application/json',
},
body: {
"client_secret" : ""+config.clientSecret_staging,
"username": ""+config.email_staging,
"password": ""+config.password_staging
}
}).then(response => {
const target = (response.body)
})
})
it('GET /capture', () => {
cy.session().then(abc =>{
cy.request({
method: 'GET',
url: '/capture/'+target
})
})
})
the goal is to capture parse of JSON array from target = (response.body)
You have two options:
leave the code as is, be aware that the
.then(response => {
const target = (response.body)
})
code isn't returning anything so the cy.session().then(abc =>{ ... code is getting the whole response (abc is the response of the first .then)
change the code into
.then(response => {
const target = (response.body)
return target // I added this return
})
and then your abc param will be equal to response.body and not to response
That's because if you don't return a subject from your chainable calls the default one will be passed to the next .then function.
Let me know if it satisfies your issue.
p.s. Welcome 👋

Cannot get post working in Angular2

So i'm trying to authenticate in my angular application. I attended headers and created an stringified body. I also looked at serveral other forum post about sending post requests in postman but i cannot get it working.
getToken()
{
console.log('started getting of token');
//get username and password from local storage
//Send username and password via body
let headers = new Headers();
let body = JSON.stringify({
name: 'test',
password: 'test'
});
headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.jwt = this.http.post('http://localhost:8080/api/authenticate/', {
headers: headers,
body: body
}).map(res => res.text()).subscribe(data => console.log(data));
}
So above is my code. I know it might be a little silly thing but I cannot get it working.
I get the error that the user cannot be found. That happens when the username is wrong, and when the username does not exsist in the database. So that a little extra tricky as well.
Who knows what the stupid mistake is that I made?
Add this code in your service.ts file.
import { Http, URLSearchParams} from '#angular/http';
getToken()
{
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let body = new URLSearchParams();
body.set('name', test);
body.set('password', test);
return this.http.post("http://localhost:8080/api/authenticate/", body, headers).map(response => response.json());
}
Use following code to send post request
this.jwt = this.http.post('http://localhost:8080/api/authenticate/',body,headers).map(res => res.text()).subscribe(data => console.log(data));
This code is what I use for post request
send_request_post(url: String, data:{})
{
var headerPost = new Headers
({
'Content-Type' : 'application/json ;charset=utf-8'
})
return this.http.post(url, JSON.stringify(data), {headers: headerPost})
.toPromise()
.then
(
response =>
{
console.log(response);
}
)
}

Resources