Sending email using axios post request to mailgun API [duplicate] - javascript

This question already has answers here:
Axios Http client - How to construct Http Post url with form params
(5 answers)
axios post request to send form data
(18 answers)
Closed 3 years ago.
I have been trying to send an email using a post request without luck. I keep getting a 401 (UNAUTHORIZED) error.
Here is my code:
axios.post('https://api.mailgun.net/v3/MY-DOMAIN/messages', {
data: new URLSearchParams({
from: 'from',
to: 'to',
subject: 'subject',
html: 'html'
}),
auth: {
username: 'api',
password: 'MY-API-KEY'
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function (response) {
console.log(response.data)
}).catch(function (error) {
console.log(error.response)
})
I've been sending post requests using axios to other API's fine.
Any ideas?
Thanks.
EDIT:
Here is the mailgun.js method I was using to create messages (which worked) but I couldn't send attachments
var mg = mailgun.client({username: 'api', key: 'MY-API-KEY'})
mg.messages.create('MY-DOMAIN', payload).then(msg => console.log(msg)) // logs response data
.catch(err => console.log(err)) // logs any error
EDIT 2: Mailgun Response
Unfortunately, you would experience issues using Javascript for things like authentication and the Access-Control-Allow-Headers. You might find that authentication (which we require) will not work with the Access-Control-Allow-Headers. We do this intentionally to forbid sending messages from front-end applications because in many cases users would hard-code their API keys and thereby expose their authentication information publicly to the Internet.

Related

I am having trouble making a simple POST Request [duplicate]

This question already has answers here:
Empty body in fetch POST request
(5 answers)
Trying to use fetch and pass in mode: no-cors
(9 answers)
Closed 3 months ago.
I am trying to do a simple call to an API endpoint using the following code and keep getting the following error:
POST net::ERR_ABORTED 400 (Bad Request)
SyntaxError: Unexpected end of input
The request options
const requestOptions = {
method: 'POST',
mode: 'no-cors',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: email,
password: password
})
};
The fetch request
await fetch("https://dev.rapptrlabs.com/Tests/scripts/user-login.php", requestOptions)
.then(async response => await response.text())
.then(response => response === "" ? {} : JSON.parse(response) )
.catch(e => {
console.log(e)
})
I am not sure what I am doing wrong.
Edit: I was only provided with the following documentation:
a. When the form has been successfully submitted passing all
validation errors, call the following API:
http://dev.rapptrlabs.com/Tests/scripts/user-login.php i. This API
endpoint needs to be called with a POST request. ii. It takes two body
params: email and password. iii. For testing purposes, use the
following email and password: test#rapptrlabs.com / Test123. iv. A
successful response will look like the following:
{ "user_id": 16,
"user_email": "test#rapptrlabs.com",
"user_username": "testuser",
"user_is_active": 1,
"user_profile_image": "http://dev.rapptrlabs.com/Tests/images/taylor_avatar.png",
"user_last_active_epoch": 1544680026,
"user_creation_epoch": 1544713200,
"user_is_new": 1,
"user_token": "6dd4737a8b7ec61313ae5e900420d46815e1d13b2902be71b97a8fbf1f421a3e" }
Edit: This issue is resolved now. The issue was that I had to use a form tag to submit the fetch request. And I have to use FormData as the request option of the fetch request.

How to use AXIOS to POST to a .php url endpoint in reactJS? [duplicate]

This question already has answers here:
Why is an OPTIONS request sent and can I disable it?
(15 answers)
Closed 1 year ago.
Running into a bad request 400 error when using axios call to endpoint ending in .php.
Code for the call looks like this
const API = {
userLogin: function () {
const email = "test#email";
const password = "Test1234";
return axios({
method: "POST",
body: {
email,
password,
},
headers: {
"Content-Type": "application/json",
},
url: "url ends in /user-login.php",
});
},
};
the email and password are different in my actual code as are is the URL, but they were giving to me as body params to pass to the endpoint. The instructions state to make the API call method "POST" and pass email and password as body params.
here is the error response i get in the picture included.
the top error is with using Fetch, and the Error that is expanded is with that axios call above. Any suggestions?
Check the Axios documentation, https://github.com/axios/axios#request-config
You probably want to put the variables you have in the body section in your code as data instead, i.e.
data: {
email,
password,
},

Translating Python API call to NodeJS Axios api call - how do I format it correctly?

I'm getting a 400 error and isAxiosError: true. I think the problem is the auth line is not formatted correctly, or I'm not quite understanding how params work in axios and what's needed by the api? What am I doing wrong in my translating of python to Axios/JS?
Here's the Voila Norbert API documentation.
Here's my Axios api call.
axios.post('https://api.voilanorbert.com/2018-01-08/search/name', {
params: {
auth: {any_string: API_KEY},
data: {
domain: 'amazon.com',
name: 'Jeff Bezos'
}
}
})
Here's the python version:
API_TOKEN = 'abcde'
req = requests.post(
'https://api.voilanorbert.com/2018-01-08/search/name',
auth=('any_string', API_TOKEN),
data = {
'name': 'Cyril Nicodeme',
'domain': 'reflectiv.net'
}
)
I am a year late with this answer but I found your question while dealing with this same error with the same API. The API documentation's suggested Python code works for me with a successful response, but I want to do it in Node and the JS code returns a 400 error. I'm sharing my solution in case it helps others in the future.
I believe the core issue is that the API expects the data to be posted as form data, not as JSON. I followed an example in another post to post form data with Axios but still was receiving a 400 error.
Then I tried posting it using the request package instead of Axios, and that results in a successful response (no error):
const request = require('request');
var data = {'name': 'Jeff Bezos', 'domain': 'amazon.com'};
request.post({
url: 'https://any_string:API_KEY#api.voilanorbert.com/2018-01-08/search/name',
form: data,
}, function(error, response, body){
console.log(body);
});
This example works when the data is included in the form: field but does not work when it is in body:
Please note the request package is deprecated and in maintenance mode.
According to their documentation, https://github.com/axios/axios, you need to give auth as a separate field, not inside params:
axios.post('https://api.voilanorbert.com/2018-01-08/search/name', {
auth: {
username: 'any_string',
password: API_KEY
},
data: {
domain: 'amazon.com',
name: 'Jeff Bezos'
}
})
Updated: removed the nesting of data in params. They should be sent as POST body, not URL params.

Unsupported grant type when getting OAuth token for Reddit API

I'm trying to get an OAuth token for the Reddit API following the Application Only OAuth instructions. My reddit app is an installed app, so for my grant_type I'm using https://oauth.reddit.com/grants/installed_client.
Currently I'm running a very short JS script to query the API and get a token:
const APP_ID = 'MY_APP_ID'
const DEVICE_ID = 'TRACKING_ID_20_TO_30_CHARS'
let form = new FormData()
form.append('grant_type', 'https://oauth.reddit.com/grants/installed_client')
form.append('device_id', DEVICE_ID)
fetch('https://www.reddit.com/api/v1/access_token', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${btoa(`${APP_ID}:`)}`,
}),
body: form })
.then(handleResponse)
.then(function(data) {
console.log(data)
})
.catch(error => console.error(error))
function handleResponse(response) {
return response.json()
}
(Note: running the snippet as-is will give you a NetworkError because the APP_ID isn't a real one and I don't want to give mine out.)
The response I get is:
{
"error": "unsupported_grant_type"
}
When I try the same API request using a REST client I get back the expected response, so this makes me think that the problem is JavaScript-related. Since the grant_type matches what the instructions say I'm not really sure what to do with the error. I'm hoping someone else more experienced with OAuth will know what is going on here.
The problem was the use of the FormData object. In earlier stages of troubleshooting I found this answer on Reddit and decided to use it, but that didn't work for me.
It was submitting the data as multipart/form-data rather than application/x-www-form-urlencoded, which Reddit's OAuth server did not like. I wrote a helper function based on this answer which did the trick:
function urlEncode(data) {
let out = [];
for (let key in data) {
out.push(`${key}=${encodeURIComponent(data[key])}`);
}
return out.join('&')
}

Vue and Axios CORS error No 'Access-Control-Allow-Origin' header is present on the requested resource [duplicate]

This question already has answers here:
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
(11 answers)
Closed 4 years ago.
I am currently getting the above error, I am using Axios to make the GET request to an external API. After reading the Mozilla docs, doing a lot of research and trying different options I am still not any better off.
I have stripped the code back to the basics:
axios.get('URL.com', {
headers: {
Access-Control-Allow-Origin: *
},
auth: {
username: 'username',
password: 'password'
},
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Do I need to add anything else to the headers?
Everything works through Postman so once I can pass the CORS issue everything will work.
baseURL: 'https://www.yourserver.com.br',
timeout: 10000,
withCredentials: false
setting axios.defaults.withCredentials = true;

Categories

Resources