Can't get response from imgur api - node.js

I'm trying to get a response from the imgur api, and I'm having trouble getting anything. I keep getting 401 not authorized errors. I've also tried using ".../gallery/authorization?client_id=###########/search="+req.body.search and that doesn't work either. I'm not really understanding the documentation. Can anyone tell me what I am doing wrong? Oh, btw this is written in express/node.js.
router.post('/getimages', function(req,res,next){
console.log('successfully got to /getimages backend :P');
console.log('the value of the search query is ', req.body.search);
var url = 'https://api.imgur.com/3/gallery/search?q='+req.body.search;
axios.get(url)
.then(function (response) {
console.log('YATA from axios to imgur');
console.log(response);
res.json({'YATA':'YATA from getimages'});
})
.catch(function (error) {
console.log('Fail from axios request to imgur');
console.log(error);
res.json({'OHNOES':'NOOOOYATA from getimages'});
});
})

According to the documentation, you have to register your app to use the API. This is even if you'll be using it in an anonymous capacity, which they seem to allow.

Put the clientId in the authorization header :
axios = require("axios");
search = "monkey";
clientId = "YOUR_CLIENT_ID";
axios({
method: 'get',
url: 'https://api.imgur.com/3/gallery/search?q=' + search,
headers: { 'authorization': 'Client-ID ' + clientId }
}).then(function(response) {
console.log(response.data);
}).catch(function(error) {
console.log(error);
});

Related

ReCAPTCHA siteverify not returning JSON response

I am implementing recaptcha into a user submittable form. After attempting to validate the token using the url
https://www.google.com/recaptcha/api/siteverify
The response given is something similar to
▼���RPP*.MNN-.V�RHK�)N�☺��▬§�↨�&秤�ģ�B#�̼�Ĝ�¶�̼��↕ݢ�����T%�d,W-�
� K
The code used to attempt to validate the response is as follows
var data = JSON.stringify({
secret: process.env.RECAPTCHA_SECRET,
response: req.body.gcaptcha_response,
});
var config = {
method: "post",
url: "https://www.google.com/recaptcha/api/siteverify",
headers: {
"Content-Type": "application/json",
},
data: data,
};
axios(config)
.then(function (response) {
res.json({
success: true,
body: response.data,
});
})
.catch(function (error) {
console.log(error);
});
I have also attempted with other content types to no success. I have also attempted to follow the answer given in this thread
This is a workaround for now
I just realised this is happening for the latest version of axios.
If you install axios version 1.1 it returns the data as json.
Thread: https://github.com/axios/axios/issues/5298

Node.js? API Authentication problems

This is what my "dev" sent me. Someone help please
I'm trying my best, but their API doesn't respond to our methods. This authentication is the root of the problem. I'm right now using Axios(the most popular and only method for making API requests for web apps) but it's not accepting request
and then i told him i would ask for help*
You can ask this question- ` How do I make requests for creating order API in my express app? I've tried to make the request by getting my form data from my EJS form using the request.body. But still, it is saying error 400.
Here is his code:
app.post('/order-labels', checkAuthenticated, (req, res) => {
const data = JSON.stringify(req.body);
console.log(data)
const config = {
method: 'post',
url: 'https://labelsupply.io/api/order',
headers: {
'X-Api-Auth': '32854090-03dd-a3c1-Deleted some for safety',
'Content-Type': 'application/x-www-form-urlencoded'
},
data: data
};
axios(config)
.then(function(response) {
console.log(response.data);
})
.catch(function(error) {
console.log(error);
});
})
by console.logging we are getting the data, but the API doesn't accepting
The API Docs are here.
you may need an account to view just put junk
The API calls for url encoded string.
const data = JSON.stringify(req.body);
console.log(data)
data = new URLSearchParams(Object.entries(data)).toString();
console.log(data); // now should be URL encoded
const config = {
method: 'post',
url: 'https://labelsupply.io/api/order',
headers: {
'X-Api-Auth': '32854090-03dd-a3c1-Deleted some for safety',
'Content-Type': 'application/x-www-form-urlencoded'
},
data: data
};
See if the API likes the new encoding?

Unable to send auth token to server axios

I am trying to set up a simple login system for a small project. I have managed to connect the website to an login api hosted locally via mysql database.
I'm using express/nodejs on backend and Vue for front end. Also using axios to send http requests.
The error i get is POST http://localhost:3001/api/get-user 422 (Unprocessable Entity)
"{"message":"Please provide the token"}"
Client side part of code.
finally{
const auth = await axios.post(`/api/get-user`, {
headers: {
Authorization: `Bearer ${this.Token}`
}
})
}
Server side part.
router.post('/get-user', signupValidation, (req, res, next) => {
if(
!req.headers.authorization ||
!req.headers.authorization.startsWith('Bearer') ||
!req.headers.authorization.split(' ')[1]
){
return res.status(422).json({
message: "Please provide the token",
});
}
const theToken = req.headers.authorization.split(' ')[1];
const decoded = jwt.verify(theToken, 'the-super-strong-secrect');
db.query('SELECT * FROM users where id=?', decoded.id, function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results[0], message: 'Fetch Successfully.' });
});
});
I have put a base URL.
The login is working 100% and I am able to extract the token from the response data.
I used Postman to send the request to the server to get the user and it works perfectly. I believe the issue is in the code of the client side or maybe the client side is sending the token incorrectly where the server side cant read it... I'm not sure please help.
The second parameter in axios post is the body
finally{
const auth = await axios.post(`/api/get-user`,{}, {
headers: {
Authorization: `Bearer ${this.Token}`
}
})
}

Not able to res.send() server response, but able to console.log the same response with Express

I'm working on a custom integration solution using Express routes and after making a fetch call to firebase I need the response to my server to be the one coming from firebase to show me any issues (such as authentication errors) coming from there.
I've been trying to display the response by using res.send(), but it throws me a "TypeError: Converting circular structure to JSON" error, but when console.logging that same response it gives me the correct response (which is an authentication error). What's the deal with that?
Here's the code:
router.route("/bankval").get (fetchAirtabeleRecords, (req, res) => {
fetch(`https://xxxxxxxxxxxx.firebaseio.com/integratedData.json?auth=${FIREBASESECRET}`,{
method: 'PUT',
headers:
{
Authorization: 'Bearer ' + FIREBASESECRET,
'Content-Type': 'application/json'
},
body: JSON.stringify({bankValuation: res.bankVal}) // correct values here
})
.then((res) => res.json())
.then(res.send(res)) // This throws me the error
.then((res)=> { console.log('response: ', res); }) // This works and displays expected "error: 'Unauthorized request.' from firebase, but it's only in console, so it's not good enough."
// .then(res.send({bankValuation: res.bankVal})) // this works, but if authentication error occurs it still displays the correct data, when it's obviously not sent to firebase. Only using this for testing purposes.
.catch(err=> { console.log('error: ',err); }) })
I'm pretty new to this, so maybe I'm doing this completely backwards or something, but any input is appreciated.
Thanks.
You override res, so try this:
.then((resp) => resp.json())
.then((resp) => res.send(resp))
.then((resp)=> { console.log('response: ', resp); })

Getting 400 Bad Request When POSTing to Get Transaction Token

I'm trying to integrate our website with Converge API with Hosted Payments Page. Here is the link to their documentation https://developer.elavon.com/#/api/eb6e9106-0172-4305-bc5a-b3ebe832f823.rcosoomi/versions/5180a9f2-741b-439c-bced-5c84a822f39b.rcosoomi/documents?converge-integration-guide/book/integration_methods/../../book/integration_methods/hosted_payments.html
I'm having troubles getting past the first step which is requesting a transaction token from their API endpoint. I'm sending a POST request from my server using axios with the correct parameters and URL, but when I try and POST i get 400 Bad Request. When I make the same request in POSTMAN I get a 200 response with the transaction token. I talked to their developers and they said that everything I was doing was correct and that nothing seemed odd within my code, so even they were stumped as to why I couldn't make a POST request to their endpoint. Obviously there is something within my code that their API is not liking, or else I wouldn't be here trying to find answers for this.
Here is how I'm making the POST request:
app.get('/converge_token_req', (request, response) => {
let params = {
ssl_merchant_id: '*****',
ssl_user_id: '*****',
ssl_pin: '*****',
ssl_transaction_type: 'ccsale',
ssl_amount: '1.00'
}
axios.post('https://api.demo.convergepay.com/hosted-payments/transaction_token', params, {
headers: { 'Content_Type' : 'application/x-www-form-urlencoded' }
}).then((res) => {
response.send(res.data)
}).catch((error) => {
console.log('there was an error getting transaction token')
response.send(error.message)
})
})
Here are the Request Headers:
I'm honestly out of ideas to try. The developers say that everything looks just fine yet I'm unable to make a successful request to their API. If anyone has any thoughts on this that would be great. Thanks!
This code below worked for me:
app.get('/converge_token_req', (request, response) => {
let params = {
ssl_merchant_id: '*****',
ssl_user_id: '*****',
ssl_pin: '*****',
ssl_transaction_type: 'ccsale',
ssl_amount: '1.00'
}
axios({
method: 'post',
url: 'https://api.demo.convergepay.com/hosted-payments/transaction_token',
params: params
}).then((res) => { response.send(res.data)
}).catch((error) => {
console.log('there was an error getting transaction token: ',
error)
})
})
I've since found out the solution to my problem. The issue here is that converge expects a x-www-form-urlencoded string that needs to be Stringified before submitting the request. I found a library that works well for this called qs and I used it like so:
let params = qs.stringify({ // need this if content_type is application/x-www-form-urlencoded
ssl_merchant_id: env.CONVERGE.MERCHANT_ID,
ssl_user_id: env.CONVERGE.USER_ID,
ssl_pin: env.CONVERGE.PIN,
ssl_transaction_type: request.query.type,
ssl_amount: request.query.amount,
ssl_email: request.query.email,
ssl_company: request.query.company,
ssl_avs_address: request.query.address,
ssl_avs_zip: request.query.zip,
ssl_description: request.query.desc,
})
axios.post('https://api.convergepay.com/hosted-payments/transaction_token', params, {
headers: {
'Content_Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).then((res) => {
response.send(res.data)
}).catch((error) => {
console.log('there was an error getting transaction token')
response.send(error.message)
})
I think you could also get away with just using JSON.stringify() but this way worked for me.

Resources