Can I make a "Mailjet" API call using fetch? - javascript

I would like to make a request to "Mailjet" API from a react app. To do so, I would like to use fetch API.
According to the documentation, I can use curl :
curl -s \
-X POST \
--user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
https://api.mailjet.com/v3.1/send \
-H 'Content-Type: application/json' \
-d '{
"Messages":[
{
"From": {
"Email": "toto#toto.fr",
"Name": "toto"
},
"To": [
{
"Email": "passenger1#example.com",
"Name": "passenger 1"
}
],
"TemplateID": 1074249,
"TemplateLanguage": true,
"Subject": "Hi there !",
"Variables": {}
}
]
}'
I tried with fetch the following code :
fetch('https://api.mailjet.com/v3.1/send',{
method : 'POST',
mode : 'no-cors',
headers : {
'Content-Type': 'application/json',
'client_id':'xxx111',
'client_secret':'xxx000'
},
body : {
"Messages":[
{
"From": {
"Email": "toto#toto.fr",
"Name": "Toto"
},
"To": [
{
"Email": "email#email.com"
}
],
"TemplateID": 1094249,
"TemplateLanguage": true,
"Subject": "Hi there",
"Variables": {
}
}
]
}
})
.then(resp=>resp.json())
.then(data => {
console.log('data mailjet', data);
})
.catch(err => err)
I always got a 401 error "not authorized". I am sure my API keys are not set properly, but I don't really know how I can set them with fetch.
Can I make this API call from my react-app or do I need to create my own API and request the resources with node?
Thanks a lot!!

Regarding Mailjet - use the node integration they provide ;)
import mailjet from 'node-mailjet';
Regarding fetch - add your token in your header, depending on what kind of token the API expects. This will differ whether with each API and wether your doing frontend or backend calls.
With Node, save the token as a environment variable and then inject into the Authorization header.

The API key & secret need to be added as a Basic auth header and base64-encoded (use any lib you'd like in Node)
const encoded = base64.encode(`${apiKey}:${apiSecret}`)
fetch('https://api.mailjet.com/v3.1/send', {
headers: {
Authorization: `Basic ${encoded}`
}
})
Docs: https://dev.mailjet.com/sms/reference/overview/authentication/

Related

Firebase messaging missing Authentication key in MongoDB trigger functions:

Please I need help. I don't know what I am doing wrong. I am trying to send push notification from http request but I keep getting this error:
The request was missing an Authentication Key. Please, refer to section "Authentication" of the FCM documentation, at https://firebase.google.com/docs/cloud-messaging/server.
I am currently doing this:
const response = await context.http.post({
url:"https://fcm.googleapis.com/fcm/send",
header:{"Content-Type": "application/json",
"Authorization":"key= Web Server Key"},
body:{
"to": usersPushToken, // From FirebaseMessaging.instance.getToken();
"notification": {
"title": "Title",
"body": "body",
"clickAction": 'FLUTTER_NOTIFICATION_CLICK',
"sound": 'default',
},
}
},
encodeBodyAsJSON: true,
});
My web server key (Cloud Messaging API (Legacy)) I also tried API key:
This was my fault (headers not header). But I will leave this answer for anyone using Flutter, MongoDB, and Firebase Messaging.
const response = await context.http.post({
url:"https://fcm.googleapis.com/fcm/send",
"headers":{"Content-Type": ["application/json"], //Must be in array
"Authorization":["key= Web Server Key"]}, //Must be in array
"body":{
"to": usersPushToken, // From FirebaseMessaging.instance.getToken();
"notification": {
"title": "Title",
"body": "body",
"clickAction": 'FLUTTER_NOTIFICATION_CLICK',
"sound": 'default',
},
}
},
encodeBodyAsJSON: true,
});

Mailchimp Api is unable to get the email_address field I send

I am tryiong to use the mailchimp API in order to subscribe a user to an existing list.
Using the node https request, I send the following request to the mailchimp server:
const url = `https://us7.api.mailchimp.com/3.0/lists/<list_id>/members?skip_merge_validation=true'`;
const options = {
method: "POST",
auth: "<name>:<API Key>",
};
const request = https.request(url, options, (response) => {
response.on("data", (data) => {
console.log(JSON.parse(data));
if (data.status === 200) {
res.redirect("/sucess");
} else {
res.redirect("/failure");
}
});
});
request.write(JSON.stringify(user_data));
request.end();
});
Before making the request, I console.log the user data collected from the front-end.
console.log("USER DATA : " + JSON.stringify(user_data));
and this is the answer i am getting from the API server :
USER DATA : {"members":[{"email_address":"a.b#email.com","status":"subscribed","merge_fields":{"FNAME":"A","LNAME":"B"}}]}
{
type: 'http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/',
title: 'Invalid Resource',
status: 400,
detail: "The resource submitted could not be validated. For field-specific details, see the 'errors' array.",
instance: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
errors: [
{
field: 'email_address',
message: 'This value should not be blank.'
}
]
}
As you can see in the log, the email_address field is not blank.
Has anyone encountered this problem before ? any Ideas ?
Thanks in advance
I've found the problem, it was related to my user data structure. It is now working with the following code
const user_data = {
email_address: req.body.email,
status: "subscribed",
merge_fields: {
FNAME: req.body.fName,
LNAME: req.body.lName,
}
}
This works
{
"email_address": "real#gmail.com",
"status": "subscribed",
"merge_fields": {
"FNAME": "Name",
"LNAME": "Last Name"
}
}
Providing CURL
curl --location --request POST 'https://us10.api.mailchimp.com/3.0/lists/audience_id/members' \
--header 'Authorization: Bearer API_KEY' \
--header 'Content-Type: application/json' \
--data-raw '{
"email_address": "real#gmail.com",
"status": "subscribed",
"merge_fields": {
"FNAME": "Name",
"LNAME": "Last Name"
}
}'

How do I convert this CURL request to a normal HTTP request Javascript

I want to use this code snippet that I got from the IBM Natural Language API but run it in Javascript. How do I go about converting this to be a normal HTTP POST request? Just some pointers on rearranging the syntax would be amazing, I know there are a few placeholders here in the code that I'll change for what I need.
$ curl -X POST -u "apikey:{apikey}" \
--header "Content-Type: application/json" \
--data '{
"text": "I love apples! I do not like oranges.",
"features": {
"sentiment": {
"targets": [
"apples",
"oranges",
"broccoli"
]
},
"keywords": {
"emotion": true
}
}
}' \
"{url}/v1/analyze?version=2019-07-12"
Thanks!
You need to clarify what you mean by javascript. If it is node.js then you can use the ibm-watson sdk - https://cloud.ibm.com/apidocs/natural-language-understanding?code=node#analyze.
There is sample code at the link to show you how.
const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
version: '2020-08-01',
authenticator: new IamAuthenticator({
apikey: '{apikey}',
}),
serviceUrl: '{url}',
});
const analyzeParams = {
'text': 'I love apples! I do not like oranges.',
'features': {
"sentiment": {
"targets": [
"apples",
"oranges",
"broccoli"
]
},
'keywords': {
'emotion': true
}
}
};
naturalLanguageUnderstanding.analyze(analyzeParams)
.then(analysisResults => {
console.log(JSON.stringify(analysisResults, null, 2));
})
.catch(err => {
console.log('error:', err);
});
If you are referring to javascript inside a browser, then what you use really depends on the javascript framework that you are using. This would be xhttp for raw javascript, but most frameworks simplify the process for you.
An alternative would be to use the ibm-watson sdk through browserify - https://github.com/watson-developer-cloud/node-sdk/tree/master/examples/browserify
or web pack - https://github.com/watson-developer-cloud/node-sdk/tree/master/examples/webpack

Getting a 422 Error on Post request, but I think my request is being sent correclty

I have to make a POST request, to an API that was given to me.
I am supposed to send some data to it and get back an JWT token.
The data i have to send is an object called data like this:
{
"firstName": "Jane",
"address": "Lohmühlenstraße 65",
"numberOfChildren": 2,
"occupation": "EMPLOYED",
"email": "jane.doe#getpopsure.com"
}
And the API docu looks like this:
curl https://challenge-dot-popsure-204813.appspot.com/user \
-H 'Content-Type: application/json' \
-d '{"firstName":"Jane","address":"Lohmühlenstraße 65","numberOfChildren":2,"occupation":"EMPLOYED","email":"jane.doe#getpopsure.com"}' \
-X POST
I am sending with axios a POST request, with an object, but i get an 422 Error:
Failed to load resource: the server responded with a status of 422 ()
This is my POST request, where data is the object above:
axios.post('https://challenge-dot-popsure-204813.appspot.com/user', data)
.then(function (response) {
debugger
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Any ideas what can be the issue?
I was able to reproduce the 422 error by removing or invalidating the JSON data. For instance remove/rename the "firstName" property.
Example:
{
"name": "Jane",
"address": "Lohmühlenstraße 65",
"numberOfChildren": 2,
"occupation": "EMPLOYED",
"email": "jane.doe#getpopsure.com"
}
Resulted In: 422 Unprocessable Entity
{
"errors": {
"firstName": [
"Missing data for required field."
],
"name": [
"Unknown field."
]
}
}
Plunker
I think the issue you are facing is that the data you are expecting is not all there when you make the axios.post resulting in the error you are seeing. Make sure that the data sent in the request contains all valid fields and values beforehand.

Unexpected token < in JSON at position 0

If I do curl, the server returns an array of posts objects, like this:
curl http://localhost/api/posts/
[
{
"id": 7,
"target": {
"body": "This is the body",
"title": "Airbnb raising a reported $850M at a $30B valuation",
"user": {
"first_name": "ben",
"last_name": "jamin"
}
}
},
{
"id": 11,
"target": {
"body": "This is the body",
"title": "Browsing the APISSS",
"user": {
"first_name": "user",
"last_name": "two"
}
}
}
]
I tried getting this using the fetch api:
fromServer() {
console.log('fromServer')
var headers = new Headers();
headers.append('Accept', 'application/json');
let a = fetch('http://test.com/api/posts/', headers)
.then(function(response) {
if (response.status !== 200) {
console.log('There was a problem. Status Code: ' + response.status);
return;
}
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
}
But I am getting this error:
Unexpected token < in JSON at position 0
SyntaxError: Unexpected token < in JSON at position 0
How can I solve this problem? Could you please help me. Thank you.
It is clear that you have some syntax error while parsing response into json object.
Remove all the comments from server json file if any.
If it is not:
I believe the response body is not json.
You're receiving HTML (or XML) back from the server, but code is enable to parse as JSON.
Check the "Network" tab in Chrome dev tools to see contents of the server's response.
Or debug using this code: (as "Jaromanda X" said)
.then(function(response) {
console.log(response);
console.log(response.status);
console.log(response.json());
console.log(response.text());
})
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
You can try adding the dataType property,just like dataType: 'html' or dataType: 'text'
Please check that your server is giving response in JSON format only. It should not be a string.
For Associative data you should start your JSON object with { not [ .
So your data should be in below format:
{
"data": [
{
"id": 7,
"target": {
"body": "This is the body",
"title": "Airbnb raising a reported $850M at a $30B valuation",
"user": {
"first_name": "ben",
"last_name": "jamin"
}
}
},
{
"id": 11,
"target": {
"body": "This is the body",
"title": "Browsing the APISSS",
"user": {
"first_name": "user",
"last_name": "two"
}
}
}
]
}
And you can get all data from response.data .
For more detail follow this link .
The wording of the error message corresponds to what you get from Google Chrome when you run JSON.parse('<...'). I know you said the server is setting Content-Type:application/json, but I am led to believe the response body is actually HTML.
"SyntaxError: Unexpected token < in JSON at position 0"
with the line console.error(this.props.url, status, err.toString()) underlined.
The err was actually thrown within jQuery, and passed to you as a variable err. The reason that line is underlined is simply because that is where you are logging it.
I would suggest that you add to your logging. Looking at the actual xhr (XMLHttpRequest) properties to learn more about the response. Try adding console.warn(xhr.responseText) and you will most likely see the HTML that is being received.
Please correct your code according to above explanation.
so, you can use with start JSON array ;
{
"array": [
{
"id": 7,
"target": {
"body": "This is the body",
"title": "Airbnb raising a reported $850M at a $30B valuation",
"user": {
"first_name": "ben",
"last_name": "jamin"
}
}
},
{
"id": 11,
"target": {
"body": "This is the body",
"title": "Browsing the APISSS",
"user": {
"first_name": "user",
"last_name": "two"
}
}
}
]
}
So the problem was this: Since I was testing it from the vagrant machine in LAN and in my hosts file I added the ip of vagrant machine as the url (test.com), the device was not able to fetch to that url. After I changed the vagrant machine to port forward and gave the original IP address of the machine, I was able to fetch the json objects. Thank you all for your help.
In my case, the port I was trying to use was already in use. I solved this issue by executing the follwing command in the command prompt in order to terminate the port.
taskkill /F /IM node.exe

Categories