Authentication error uploading Images to Imgur - reactjs

const data = new FormData();
data.append("image", uploadedimage);
console.log(data);
axios
.post("https://api.imgur.com/3/image/", data, {
headers: {
Authorization: `Client-ID ${apiKey}`,
},
})
.then((res) => {
console.log(res);
});
I have this code set up inside of my react app. I can't figure out why I keep getting this authentication error.
{
"data": {
"error": "Authentication required",
"request": "/3/image/",
"method": "GET"
},
"success": false,
"status": 401
}
I know my API-Key and uploaded image is good but for some reason this code is not getting through. Any help would be greatly appreciated. I am look at this in the imgur api docs,
curl --location --request POST 'https://api.imgur.com/3/image' \
--header 'Authorization: Client-ID {{clientId}}' \
--form 'image=R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'

I found this in the Axios docs here, not sure if it'll help or not.
enter link description here
// Set config defaults when creating the instance
const instance = axios.create({
baseURL: 'https://api.example.com'
});
// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

Related

Next JS Axios: fetch API data with key for CoinMarketCap

No big experience with NextJS/React. I've been readings posts about this topic, but nothing seems to work for me.I am trying to learn how curl request work using Axios in Nextjs. so I am trying to to fetch data from an Coinmarketcap API using Axios and it requires a key. I don't know how to pass it through axios. I tested the curl request and it worked. but the axios request doesn't work.
This is the curl request
curl -H "X-CMC_PRO_API_KEY: api-key-here" -H "Accept: application/json" -d "start=1&limit=5000&convert=USD" -G https://sandbox-api.coinmarketcap.com/v1/cryptocurrency/listings/latest
and this is my code IN nextJS
useEffect(() => {
console.log("running effect");
axios
.get(
"https://sandbox-api.coinmarketcap.com/v1/cryptocurrency/listings/latest",
{
params: {
start: "1",
limit: "5000",
convert: "USD",
},
headers: {
"X-CMC_PRO_API_KEY": "api-key-here",
Accept: "application/json",
},
}
)
.then((res) => {
console.log(res);
});
}, []);
the errors I get
Access to XMLHttpRequest at 'https://sandbox-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1&limit=5000&convert=USD' from origin 'http://localhost:3000' 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.
GET https://sandbox-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1&limit=5000&convert=USD net::ERR_FAILED```

How to send body data with headers with axios get request

I am trying to get request from api that has a owner = value and date = value. Using Postman I can send a request with body json to get results. However when using Axios I can not get the results. How do I send body json to header and get results back. with Axios I am getting an empty response
does not work
var searchRecord = {
owner: 'wxTWH8zqSwaIXPAVsjZoRCkvjx73',
date: '2021-09-02',
};
var config = {
method: 'get',
url: 'http://localhost:3000/records/owner',
headers: {
'Content-Type': 'application/json',
},
body: searchRecord,
};
axios
.get('http://localhost:3000/records/owner', config)
.then(function (response) {
// handle success
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
})
in Postman I can send the following in the body and get the results I need
{
owner: 'wxTWH8zqSwaIXPAVsjZoRCkvjx73',
date: '2021-09-02',
}
output response will be:
{
"instantMessage": "false",
"isComplete": false,
"_id": "612e5cede496ce8f1b6a244c",
"date": "2021-08-31",
"title": "Ming first",
"description": "Test",
"remindTime": "1630432800",
"owner": "wxTWH8zqSwaIXPAVsjZoRCkvjx73",
}
I think I have the same problem.
When I'm using the postman to test my backend - everything work ok.
So the purpose is to get data from endpoint (and as body I want to provide user email):
data = {
"user_email": test#test.com
}
.get("api/test_endpoint/", config, data)
How to send body data and headers with axios get request?
Last comment in above topick "GET Body is allowed by the standards past 2014".
So finally is it possible or is it a correct practice?
Edit:
Of course I have to add:
It's possible to add needed data as part of get request url (but it's could not be login or pass!!!)
So for example logged in admin user has possibility to get data for some user via email like:
get('localhost/api/test_endpoint?user_email=test#test.com')
So why not use body as part of get request?

Netlify, Lambdas, Stripe, and Googlebots

Ive been working on an SPA with React that i have deployed on Netlify. The application uses stripe.js as a form of payment. While all of the functionality of stripe appears to be working fine on the user side, we are running into a problem with Google Search Console. It seems that the Googlebot Crawler is being blocked by the Stripe robots.txt file. basically the ultimate goal is to be approved for google adsense and after numerous rejections (even with prerendering and a lot more content added) we are still getting rejected. when we tried the google search console to see what google bot crawlers see we have absolutely no errors, the site is mobile friendly BUT we are getting this error that is shown below. While I obviously don't have any control over their use of Stripes robot.txt file, the Search console is also telling me this:
Message:
Access to XMLHttpRequest at 'https://m.stripe.com/6' from origin 'https://m.stripe.network' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Source:
https://m.stripe.network/inner.html#url=https%3A%2F%2Fwww.stateiqtest.org%2F&title=&referrer=&muid=NA&sid=NA&version=6&preview=false:0
The last thing i want to mention is all of the stripe functionality is accessed and called from a serverless Lambda function through netlify... I am confused why the CORS issue is a policy for the bot but not for users of the site? I am attaching my stripe lambda function call which I just enabled the cors policy for... but once again ... why do i have to even do this? if im not getting errors in the console from the user side how come the bot can't access it? i have tried everything from changing my netlify.toml file to adding a robots.txt file which disallows the provided Stripe URL. any leads? let me know! your help is already appreciated ! :)
//client sides
import {loadStripe} from "#stripe/stripe-js"
export async function handleFormSubmission(event) {
event.preventDefault();
const form = new FormData(event.target);
const data = {
sku: form.get('sku'),
quantity: Number(form.get('quantity')),
};
const response = await fetch('/.netlify/functions/create-checkout', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Methods": "GET, POST",
},
body: JSON.stringify(data),
}).then((res) => res.json())
const stripe=await loadStripe(response.publishableKey);
const {err}=await stripe.redirectToCheckout({
sessionId:response.sessionId
})
if(err){
console.log(err)
}
}
im honestly going to admit i haven't used stripe in a while and haven't had issues until now thus am revisiting code. here is another function that i believe makes the request and creates the stripe checkout...
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const inventory = require('./data/products.json');
exports.handler = async (event) => {
const { sku, quantity } = JSON.parse(event.body);
const product = inventory.find((p) => p.sku === sku);
const validatedQuantity = quantity > 0 && quantity < 2 ? quantity : 1;
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
billing_address_collection: 'required',
success_url: `${process.env.URL}/success`,
cancel_url: process.env.URL,
line_items: [
{
name: 'Cognitive Analysis',
currency:'USD',
amount: 299,
quantity: 1
},
],
});
return {
statusCode: 200,
body: JSON.stringify({
sessionId: session.id,
publishableKey: process.env.STRIPE_PUBLISHABLE_KEY,
}),
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Methods": "GET, POST",
}
};
};

Mocking Postman GET request using axios is giving different results

I am trying to mock up the following request , which I have in Postman, into Axios:
in terms of cURL:
curl --location --request GET 'http://url' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer blablabla' \
--data-raw '{
"category":{
"value": "category1"
}
}'
in terms of Nodejs-Request:
var request = require('request');
var options = {
'method': 'GET',
'url': 'http://url',
'headers': {
'Content-Type': 'application/json',
'Authorization': 'Bearer blablabla'
},
body: JSON.stringify({"category":{"value":"category1"}})
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
Note: the first two codes had been generated by Postman.
When I send this request via Postman, and dump the request parametes on the server, I will get the following result:
array:1 [
"category" => array:1 [
"value" => "category1"
]
]
in terms of Axios:
var config = {
params: {
category:
{
value: 'category1'
}
},
headers: {
'Authorization': 'Bearer blablabla'
}
};
return Axios.get('http://url', config);
While dumping the parameters sent via Axios will generate the following result:
array:1 [
"category" => "{"value":"category1"}"
]
Note the difference between the two results, where the value of the category in the first result is an array, but its a string in the second !!
How I can fix my Axios request to get the same result as same as the Postman request?

How to send an SMS using Twilio through frontend with react?

I've read the Twilio documentation and I can't find a way to send a simple SMS from the frontend using JavaScript/React.
The Twilio documentation just shows how to do that using Node.js(server side).
Actually, I found the documentation a bit awkward because they don't explain the how to do that using the most common programme language on the web.
I'm using postman and it works fine, but on my react code doesn't.
The code below was exported from Postman:
var settings = {
"async": true,
"crossDomain": true,
"url": "https://api.twilio.com/2010-04-01/Accounts/AC62761f2bae5c5659cc5eb65d42e5d57e/Messages.json",
"method": "POST",
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic hashedAuthToken",
"Cache-Control": "no-cache",
"Postman-Token": "0s41f5ac-2630-40c4-8041-1e5ee513f20d"
},
"data": {
"To": "+353838173123",
"From": "+18634000432",
"MessagingServiceSid": "MG3d622e63a343e11a2032b1414560f227",
"Body": "Test, hi"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
PS: The tokens above was modified. It won't work if you are not using your own credential.
Twilio developer evangelist here.
There is a huge problem with what you are trying to attempt here.
Putting your Twilio credentials into the front end (or into a Stack Overflow question/answer) leaves them open to anyone to read your source code and steal them. A malicious attacker can take those credentials and abuse your account with them.
I recommend you refresh your Auth Token in your Twilio console now. You should consider them compromised.
What you should do is build an SMS sending service on your own server side and then call that service from your React front end. There is a blog post on sending SMS with Twilio on React that is worth reading and I will try to put something together to show it too.
Update:
I wrote a blog post explaining how to send an SMS with React and Twilio. The important thing is that you should perform the API call in your server (in the blog post, it's an Node.js/Express server but you can use whatever server-side tech you want). Then you send the message from your React application to the server using fetch (or axios or XMLHttpRequest if you want).
You can use the method below to do that easily.
sendSMSTwilio(message) {
const url = Config.sms.url;
const accountSid = Config.sms.accoundId;
const authToken = Config.sms.authToken;
const auth = 'Basic ' + new Buffer(Config.sms.accountSid + ':' + Config.sms.authToken).toString('base64');
const details = {
To: message.to,
From: message.from,
MessagingServiceSid: Config.sms.serviceSid,
Body: message.text
};
const formBody = [];
for (var property in details) {
const encodedKey = encodeURIComponent(property);
const encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + '=' + encodedValue);
}
const body = formBody.join('&');
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
Authorization: auth
},
body
};
return new Promise((resolve, reject) => {
return fetch(url, options)
.then((response) => {
return resolve(response);
})
.then((responseJson) => {
return resolve(responseJson);
})
.catch((error) => {
return reject(error);
});
});
}
You can call and receive the promise response like that:
this.sendSMSTwilio()
.then((data) => {
console.log(data);
})
.catch((err) => {
console.log('Error SMS sender', err);
});

Resources