Adding Subscriber to Mailchimp Using Api 3.0 Using Javascript - javascript

I'm trying to add an subscriber to my Mailchimp list when the following meteor method runs.
I'm getting an error: Parameter "url" must be a string, not object.
import { Meteor } from "meteor/meteor";
import { check } from "meteor/check";
import { Logger } from "/server/api";
import request from "request";
import fetch from "isomorphic-fetch";
const methods = {
"myproject/addToMailchimp": (email) => {
check(email, String);
Logger.info(`contact person at ${email}`);
const request2 = request("https://us16.api.mailchimp.com/3.0/lists/<LISTID>/members", {
method: "POST",
headers: {
"content-type": "application/json"
},
mode: "no-cors",
json: {
email_address: email,
status: "subscribed"
},
redirect: "follow",
auth: {
user: "<USERNAME>",
pass: "<APIKEY>"
}
});
fetch(request2).then((data) => {
console.log(data);
});
}
};
Meteor.methods(methods);
I would really appreciate any help on this. I've never used fetch or request before, so I reckon I'm not using these correctly.
Thanks!
Will

Related

Symfony Api Platform not showing the api page correctly

I am working on an existing project that was created by someone in Vue.js and Symfony. Right now I am trying to integrate "the login" module but it is not working. Specifically, I cannot login. In the Login.vue file there is an API calling for login /api/login.
Here is current code:
async Login() {
const data = { username: this.email, password: this.password };
this.loading = true;
const response = await fetch(
"/api/login",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}
);
console.log('333', response)
let newtoken = response.token
this.$store.dispatch("loginSuccess", response.token);
await this.getMyProfile(newtoken);
if (this.$route.query.r) {
await this.$router.push({ path: this.$route.query.r });
//window.location.href = this.$route.query.r;
} else {
await this.$router.push({ path: "/center" });
// window.location.href = "/center";
}
},
But I think the API is not working. Should I set any base_url in any file? Here is my .env file. Where I am wrong?
DATABASE_URL="mysql://root:#127.0.0.1/dating_sugar_sta?serverVersion=mariadb-10.4.25&charset=utf8"

Vue.JS POST request pass null bearer token and failed with status code 401

I'm backend guy who wants to gain some Vue.js skills. In my app I've got Ruby on Rails as backend and Vue.js as front-end with a standard JWT token flow. I'm trying to send a POST request (fetchAllProductsRequest) to the backend that will trigger some background job using below code:
index.js
const fetchAllProductsRequest = (self) => {
const jwtToken = self.$store.state.idToken;
return axios
.post(`/api/v1/imports/products/fetch_all`,{
headers: {
Authorization: `Bearer ${jwtToken}`,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(response => response.data)
};
Quite surprisingly I get an error: Request failed with status code 401. When I debugging it on the backend side I see that I send an empty token inside the header:
[1] pry(#<Api::V1::Imports::ProductsController>)> params[:headers]
=> #<ActionController::Parameters {"Authorization"=>"Bearer null", "Content-Type"=>"application/json", "Accept"=>"application/json"} permitted: false>
Here is a function that triggers fetchAllProductsRequest which is responsible for POST request:
fetch_all.vue
<script>
import {
fetchAllProductsRequest,
} from '../../api/imports'
import ModalController from '../general/modal_controller'
export default {
name: 'BackboneFetchAll',
data() {
return { }
},
components: {
MoonLoader
},
computed: {
databaseSyncInProgress() {
return this.$store.getters.getDatabaseSyncStatus;
},
},
methods: {
async syncAll() {
let confirmationText = `Do you want to sync all Backbone products?`
if (await ModalController.showConfirmation('Confirmation', confirmationText)) {
try {
ModalController.showLoader()
await fetchAllProductsRequest(this)
this.$store.commit('setSyncingProductsInProgress', value)
const successMessage = `Database synchronization has been queued`
await ModalController.showToast('', successMessage)
} catch (data) {
const errorMessage = `Error occurred during queueing products to sync - `
ModalController.showToast('', errorMessage + data?.message, 'error')
} finally {
ModalController.hideLoader()
}
}
},
}
}
</script>
What did I missed?

Vue Login with Axios Request HTTP

Im new at Vue and im trying to make a Request HTTP to my backend,
When i inspect in my browser, i get the access token from /login but in the api/users i get "Token is Invalid". How do i get my api/users data?
import axios from "axios";
export default {
name: "login",
async created() {
const response = await axios.get("api/users", {
headers: {
Authorization: "Bearer " + localStorage.getItem("token")
}
});
console.log(response);
},
data() {
return {
showError: false,
email: "",
password: "",
};
},
methods: {
async EnvioLogin() {
try {
const response = await axios.post("api/auth/login", {
email: this.email,
password: this.password,
});
localStorage.setItem("token", response.data.token);
const status = JSON.parse(response.status);
if (status == "200") {
console.log(response);
this.$router.push("intermediorotas");
}
} catch (error) {
this.showError = true;
setTimeout(() => {
this.showError = false;
}, 3000);
}
},
},
You can create a service to make call to backend, i guess the problem is the url http://localhots:3000/api, you missed this part http://localhots:3000
import axios from 'axios'
const client = axios.create({
baseURL: 'http://localhots:3000/api',
headers: {
'Content-Type': 'application/json',
},
})
export default client
then import the service
import myService from './myService'
await myService.get(`/auth/login`, {})

fetch() injecting a query variable/header value to every call

Right now, in my React-Native app I have the following:
fetch('http://localhost/SOMETHING', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer '+this.state.authtoken
}
})
Goal: Have my API know what UID is making the call. I know this should be in authtoken but different users can have the same authtoken.
My initial thought is to add a ?uid=${UID} to the end of every url. However, I have GET, POST, PATCHs, with their own set of queries
Another thought would be add a header value with the UID data.
Regardless of what I choose, it would be awesome to be able to add this value to every FETCH without having to do much else work.
Is this something that is possible? Open to suggestions on what you would do.
If You can then best would be to switch to Axios (https://github.com/axios/axios) - it's much easier to do that there.
But if You need to use fetch then https://github.com/werk85/fetch-intercept is your solution.
Example code
fetchIntercept.register({
request: (url, config) => {
config.headers = {
"X-Custom-Header": true,
...config.headers
};
return [url, config];
}
});
Not sure if you're willing to step away from fetch, but we use apisauce.
import { create } from 'apisauce';
const api = create({
baseURL: 'http://localhost',
headers: { 'Accept': 'application/json' },
});
api.addRequestTransform(request => {
if (accessToken) {
request.headers['Authorization'] = `bearer ${accessToken}`;
}
});
api.get('/SOMETHING');
edit
If you want to keep it close to fetch, you could make a helper function.
let authToken = null;
export const setAuthToken = token => {
authToken = token;
};
export const fetch = (url, options) => {
if (!options) {
options = {};
}
if (!options.headers) {
options.headers = {};
}
if (authToken) {
options.headers['Authorization'] = `Bearer ${authToken}`;
}
return fetch(url, options);
};
You will probably only use the setAuthToken function once.
import { setAuthToken } from '../api';
// e.g. after login
setAuthToken('token');
Then where you would normally use fetch:
import { fetch } from '../api';
fetch('http://localhost/SOMETHING');
I would not consider creating a onetime helper function and an extra import statement for each fetch a lot of "extra work".
You can build a wrapper function for fetching with uid
function fetchWithUid(baseUrl, uid, authtoken, options) {
const { method, headers, body, ...rest } = options;
const fetchOptions = {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + authtoken,
...headers,
},
method,
...rest,
};
if (body) {
fetchOptions.body = JSON.stringify(body);
}
return fetch(`${baseUrl}?uid=${uid}`, fetchOptions);
}
Use the fetchWithUid function like this, the fetchOptions just mimic the original fetch function's option.
const fetchOptions = {
method: 'POST',
body: {
hello: 'world',
},
};
fetchWithUid('http://localhost/SOMETHING', 123, 'abcd', fetchOptions);

ember-simple-auth custom authorizer not called with ember-django-adpter

I am using ember-django-adapter with ember-simple-auth and have written the custom authorizer for token authentication. I am able to obtain the token from server but not able to inject it into the api requests using the adapter.
app/authorizers/application.js
import Ember from 'ember';
import Base from 'ember-simple-auth/authorizers/base';
const { service } = Ember.inject;
export default Base.extend({
session: service('session'),
init: function () {
console.log('Intialize authorizer');
},
authorize(data, block) {
const accessToken = data['access_token'];
if (this.get('session.isAuthenticated') && !Ember.isEmpty(accessToken)) {
block('Authorization', `Token ${accessToken}`);
console.log("authorizer called with token: " + accessToken);
}
}
});
app/adapters/application.js
import Ember from 'ember';
import DRFAdapter from 'ember-django-adapter/adapter/drf';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
const { service } = Ember.inject;
export default DRFAdapter.extend(DataAdapterMixin, {
session: service('session'),
authorizer: 'authorizer:application'
});
app/authenticators/token.js
import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';
export default Base.extend({
serverTokenEndpoint: 'http://localhost:8000/ember-auth/',
authenticate: function(email, password) {
return new Ember.RSVP.Promise((resolve, reject) => {
Ember.$.ajax({
url: this.serverTokenEndpoint,
type: 'POST',
data: JSON.stringify({
email: email,
password: password
}),
contentType: 'application/json;charset=utf-8',
dataType: 'json'
}).then(function(response) {
console.log('Got token: ' + response.token);
Ember.run(function() {
resolve({
token: response.token
});
});
}, function(xhr) {
var response = xhr.responseText;
Ember.run(function() {
reject(response);
});
});
});
},
invalidate: function() {
console.log('invalidate...');
return Ember.RSVP.resolve();
}
});
Ember tries to transition to protected route but due to non injection of Authorization header the request fails with 403 error.
Any help is appreciated.

Categories

Resources