Problem to integrate send in blue api with my nestjs application - node.js

Describe the bug
Problem to integrate sendinblue api with my nestjs app. I need to integrate with a custom authentication and in the axios's api says that i need to use a header for custom authentication, in postman i'm using api key for authorization and it works,but it throws a error 401.
To Reproduce
async SendEmailToSendInBlue(email: {
sender: { email: string };
to: [{ email: string }];
subject: string;
textContent: string;
}): Promise<any> {
const url = `${SENDINBLUE_URL}`;
return this.httpService
.post<any>(url, email, {
headers: {
Key: 'api-key',
Value: process.env.SENDBLUE_API_KEY,
'Add To': 'Header',
},
/* auth: {
username: 'apikey',
password: process.env.SENDBLUE_API_KEY,
}, */
})
.toPromise()
.then((data) => {
return data;
});
}
Expected behavior
Send an transational email to client.
Environment
-Axios Version 0.19.2
-Node.js Version 14+
-Docker Version 19.03.12-ce
-Additional Library Versions
Additional context/Screenshots
enter image description here
enter image description here

The Sendinblue documentation itself explains how to do this.
The link below explained how to pass api-key in header:
https://developers.sendinblue.com/docs/send-a-transactional-email#send-a-transactional-email-using-a-basic-html-content
headers: {
'api-key': 'YOUR_API_KEY'
}

Related

How to login using Nuxt-auth module with a Node back and mongoDB

I'm currently creating an auth system using Mongo as database, Node with express as backend, and Nuxt as frontend.
I've found this authentication module https://auth.nuxtjs.org/ followed the doc, and the youtube video. I'm using Local scheme for Jwt system.
My issue is the login doesn't work successfully.
I think it doesn't work because of my user route on the backend, but not sure about that.
I also read that their is a user.autoFetch but dont know how to use it.
nuxt.config.js
modules: [
// https://go.nuxtjs.dev/axios
'#nuxtjs/axios',
'#nuxtjs/auth'
],
// Axios module configuration: https://go.nuxtjs.dev/config-axios
axios: {
baseURL: 'http://localhost:3000/'
},
auth: {
strategies: {
local: {
endpoints: {
login: { url: 'api/auth/login', method: 'post', propertyName: 'token' },
user: { url: 'api/auth/user', method: 'get', propertyName: 'data.attributes' },
logout: false
},
tokenType: ''
}
}
},
login.vue
async submit() {
try {
let response = await this.$auth.loginWith('local', { data: this.login })
console.log(response)
} catch (err) {
console.log(err)
}
// await this.$router.push('/dashboard');
},
The response send me back a 200 status, a token, and the userId (which is in my db) but the $auth still send me loggedIn at false and I can't get information like $auth.user.email.
I tried to change the auth endpoints in the nuxt.config.js
Changed tokenType: '' to tokentype: 'Bearer'
Changed the #nuxtjs/auth version to the same as the video tutorial. (4.8.4)
I added a controller for the route user :
route :
router.get('/user', userCtrl.getUser);
controller:
exports.getUser = (req, res, next) => {
User.findOne({ _id: req.params.id })
.then(thing => res.status(200).json(thing))
.catch(error => res.status(404).json({ error }));
}
Do not hesitate to ask me more details, on the configuration, other parts of the code, or anything like that.
Thank you in advance for any kind of help !

How to add a contact to ActiveCampaign using API v1 contact_sync/contact_add

I am having trouble adding a contact to ActiveCampaign. I read a post in here: How to add a contact to a list in ActiveCampaign API v3 and am using v1 of the API. I used their contact_sync documentation to the best of my availability.
I'm developing using Gatsby/React --> GitHub --> Netlify, using a lamda function for the POST request.
Here is my axios POST:
{
method: 'post',
url: 'https://ACCOUNT.api-us1.com/admin/api.php?api_key=xxxxxxxxxxxx&api_action=contact_sync&api_output=json',
headers: { 'Content-Type': 'Content-Type: application/x-www-form-urlencoded' },
body: {
email: 'email#email.com',
first_name: 'John'
}
}
And received the following response:
{
result_code: 0,
result_message: 'Could not add contact; missing email address',
result_output: 'json'
}
I'm talking to their endpoint. I just can't figure out how to feed the endpoint the email address?
Does anyone have a working example they would be kind enough to share? Guidance of any kind would be greatly appreciated!
I wanted to make sure to close this and share my answer.
Thanks so much to #reza jafari for his comment in this post where he brought to my attention the code window on the right margin of Postman where you can choose the language/server from a dropdown and it provides the correctly formatted response.
(I don't have enough reputation to upvote #reza's response so wanted to acknowledge it here.)
I was able to get my post working in Postman, and this little trick squared me away. I'll go ahead and post my solution to close this post.
const axios = require("axios")
const qs = require("qs")
exports.handler = async function (event) {
const { email, first_name } = JSON.parse(event.body)
const data = qs.stringify({
email: email,
first_name: first_name,
tags: '"api"',
"p[1]": "1",
})
const config = {
method: "post",
url: "https://ACCOUNT.api-us1.com/admin/api.php?api_key=xxxxxxxxx&api_action=contact_sync&api_output=json",
headers: {
"Api-Token":
"xxxxxxxxx",
"Content-Type": "application/x-www-form-urlencoded",
},
data: data,
}
try {
const response = await axios(config)
return {
statusCode: 200,
body: JSON.stringify(response.data),
}
} catch (err) {
return {
statusCode: 500,
body: JSON.stringify(err),
}
}
}

Syntax error when trying to fetch jwt key in Node.js and React

I have been trying to get jwt token from REST API I implemented, but every time I try to do it accordingly to tutorials I found online I get an error. I have been searching for this problem 4 hours now but I was unable to find a solution. I read all other questions and tutorials like: How do I store JWT and send them with every request using react. Sadly every found foulution didn't work in my case. I would be grateful if you could at least tell me where can I learn to do it. I have been using REST API I created with Node.js Express in which there is method to generate JWT:
userSchema.methods.generateAuthenticationToken = function () {
const token = jwt.sign(
{ _id: this._id, admin: this.admin, premium: this.premium },
config.get(`jwtPrivateKey`)
);
return token;
};
I try to fetch data in React like this:
await fetch("http://localhost:1234/api/auth", {
method: "POST",
body: JSON.stringify(item),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
})
.then(function (response) {
return response.json();
})
.then(function (data) {
localStorage.setItem("user-info", data.token);
});
Here is error I receive:
Uncaught (in promise) SyntaxError: Unexpected token e in JSON at position 0
And here is JWT key that was generated:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MGE2YTg4YzQzZDU2MzIwMjg1NWZlZjIiLCJhZG1pbiI6dHJ1ZSwicHJlbWl1bSI6dHJ1ZSwiaWF0IjoxNjIyMTMzMzAwfQ.CmQRtSaZc8g3TEF6R7flpJ9499QnfzlfgPNVazFaUsY
Try returning an object instead of a string from your express endpoint, for example:
const token = jwt.sign(
{ _id: this._id, admin: this.admin, premium: this.premium },
config.get(`jwtPrivateKey`)
);
return { token };
};

Failing HTTP "Post" Request from GitHub Pages

I'm currently building my own website that is hosted on GitHub Pages.
The app is built with react.js and what is shown here is a contact form.
The problem I'm encountering is that I cannot send a POST request to a google cloud platform with the cloud function service through the form on the GitHub pages.
Am sure the node.js code on GCP is working since i've used Postman to send a request.
With the GCP log, the function is able to parse the POST:
GCP Success with Postman
GCP Failure from website
// react code
submitForm(event) {
const {name, email, subject, message} = this.state;
console.log("sending email...");
console.log(JSON.stringify({name: name, email: email, subject: subject, msg: message}));
fetch('GCP_API_HTTP', {
method: 'POST',
headers: { 'content-type': 'application/json', },
body: JSON.stringify({ name: name, email: email, subject: subject, msg: message })
}).then((response) => {
if (response.status === 200) {
return response.text();
} else {
this.setState({emailError: true});
return response.text();
}
})
}
Here's what's on GCP:
// GCP
const sgMail = require('#sendgrid/mail');
sgMail.setApiKey('API_KEY');
exports.contactMe = (req, res)=> {
let jsonBody;
switch (req.get('Content-Type')) {
// '{"name":"John"}'
case 'application/json':
jsonBody = req.body;
break;
// 'John'
case 'text/plain':
jsonBody = req.body;
break;
// 'name=John' in the body of a POST request (not the URL)
case 'application/x-www-form-urlencoded':
jsonBody = req.body;
break;
}
let msg = {
to: 'example#gmail.com',
from: { email: jsonBody.email, name: jsonBody.name },
subject: jsonBody.subject,
text: jsonBody.msg
};
sgMail.send(msg);
res.send("received!");
res.end();
};
It is quite critical to understand that GitHub Pages publishes any static files that you push to your repository. And it's also keen to note that...
GitHub Pages does not support server-side languages e.g. nodejs, python etc.
Since POST requests require server-side communication, you'll need to get an actual server host. Here's a good read about Static sites by GitHub Pages

Mailchimp: The API key provided is linked to a different datacenter

I am trying to update a Mailchimp list but receive the following error:
{
"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/",
"title":"Wrong Datacenter",
"status":403,
"detail":"The API key provided is linked to a different datacenter",
"instance":""
}
However, the data-center referenced in my request URL is the same (us14) as the one suffixing my API key.
request.put({
url: 'https://us14.api.mailchimp.com/3.0/lists/xxxxxxxxx/members/',
auth: {
user: 'apikey:xxxxxxxxxxxxxxxxxxxxx-us14'
},
data: {
email_address: email,
status_if_new: 'subscribed',
email_type: 'html'
}
}
I have tried generating new API keys to no avail (they're all in us14).
Ok I was able to get this to work by first passing your API Key via the headers object. Second, I wrapped my data in JSON.stringify to ensure MailChimp was receiving a proper JSON Object on post. See below for sample code, hope this helps:
request.post({
url: 'https://usXX.api.mailchimp.com/3.0/lists/xxxxxxx/members',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxxxxxxx-usXX'
},
form: JSON.stringify({
email_address: req.body.email,
status: 'subscribed',
interests: { 'xxxxxxx': true } // Interest Group
})
}, function(err, httpResponse, body) {
res.send(body);
});
const options = {
method: "POST",
auth: "uname:apikey656a******d2dfdb37c071a7cc-us19" //Should not give a space after a colon after uname
}
I had given a Space after the colon of uname. Now the API is working fine

Resources