Angular7 Consume Mailchimp RESTFUL API - httpclient

I'm trying to make HTTP POST request to consume Mailchimp API (From Angular7 code)
but i'm getting this response:
Access to XMLHttpRequest at 'https://us12.api.mailchimp.com/3.0/lists/ddddddd/members' from origin 'http://localhost:4200' 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.
From REST client i'm able to make insert in Mailchimp without having this CROS issue
export class MyService {
constructor(public httpRequestsService: HttpRequestsService) { }
private async getHttpHeader() {
const rheaders = new HttpHeaders({
'Content-Type': 'application/json' ,
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
'Access-Control-Allow-Headers':'X-Requested-With',
'Authorization': 'apikey ' + MailchimpSettings.API_KEY
});
return { headers: rheaders };
}
public async AddNewMember(email: string, language = 'en', status = , mergeFields?: any) {
var url = MailchimpSettings.URL;
var body = {
"email_address": email,
"status": MailchimpSettings.SUBSCRIBED_STATUS,
"language": language
};
var httpOptions = await this.getHttpHeader();
var _body = JSON.stringify(body);
var result = await this.post(url, _body, httpOptions);
}
public async post(url: string, body: string | {} = {}, requestHeaders?: any): Promise<Response> {
return this.http.post(url, body, requestHeaders).toPromise()
.then((res: any) => {
return res;
})
.catch((err) => {
return this.handleErrorPromise(err);
});
}
}
Anyone who can help me with right HTTP headers (or any required change) to reproduce exactly REST client behavior and be able to make a successful POST.
Thanks for your help

Unfortunately, the answer is you can't. Mailchimp does not support CORS because that would require passing API credentials, and that is not secure.
The option is to make requests from another server like you mentioned from the REST client or make a custom signup form that will use more restricted API call.
Or use jsonp request for mailchimp form clients.
See this

Related

When making a request to the Vision API Product Search an error occurs "message": "The request is missing a valid API key."

When I register a service account for the Vision API Product Search there's a json file downloaded into my desktop that has the private key. However, when making a request into this api there's no place to send that JSON. I'll show you the documentation and my code.
I didn't understand also what is the curl request and how to send it using the http post request.
And This is my code:
Future<void> uploadProductSet() async {
var projectId = 'estoOne';
var locationId = 'europe-west1';
var url = 'https://vision.googleapis.com/v1/projects/$projectId/locations/$locationId/productSets';
final responseOne = await http
.post(Uri.parse(url),
body: json.encode({
'displayName': 'Product-Set-One',
}))
.catchError((error) {
throw error;
});
print(resoinseOne.body);
}
You have to send your access token with the Authorization header.
The API seems to use the Bearer authentication method.
So set the following header in your http request: Bearer $authToken
You should get the auth-token from the credentials file you've downloaded
So your code should look something like this: (untested)
await http.post(Uri.parse(url),
headers: { 'Authorization': 'Bearer $authToken' },
body: json.encode({
'displayName': 'Product-Set-One',
})).catchError((error) {
throw error
})

How can I reach the 'Retry-After' response header using axios?

I'm building a simple Vue2 app with Auth section, which makes requests to REST API service.
So, I have my axios instance:
const instance = axios.create({
baseURL: BASE_URL,
timeout: DEFAULT_TIMEOUT,
withCredentials: true,
headers: {
accept: 'application/json',
},
});
To make authorization requests I use a separate module:
const auth = (api) => ({
submitPhoneNumber({ userPhone }) {
return api.get(`auth/${userPhone}`);
},
});
And set it all up together like this:
export default {
auth: auth(instance),
};
Then I add my api to Vue as a plugin:
export default {
install(Vue) {
const vueInstance = Vue;
vueInstance.prototype.$api = api;
},
};
In the component I access my api-plugin and make a request, extracting status and headers from it:
const { status, headers } = await this.$api.auth.submitPhoneNumber({
userPhone: this.userPhone,
});
When I look through the response in chrome devtools, I clearly see a "retry-after" header with number of seconds, after which I can make another request.
Upon receiving the response, I would like to save this number of seconds to some variable and then render a warning message like "Please wait { seconds } to make another submit".
The problem is that in my code I have no such header in the response (while I can see it in devtools, a I said):
see the screenshot
So, when logging the headers from my response, there are just these:
{content-length: '19', content-type: 'application/json; charset=utf-8'}
What is the problem with that?
Try var retrysec = error.response.data.retry_after that worked for me

Stripe Metadata submission invalid object

I am implementing Stripe payments, but am unable to submit metadata as a query param as per the documentation, it seems as though it wants iterable stringified key-value pairs which I have tried to achieve with the below with no luck.
Question: How can I pass metadata to Stripe using Dart and the HTTP library?
class StripeServices {
static var client = http.Client();
static var stripeTestKey =
'privatesecretkeyfromstripe';
static Future<void> createStripeCustomer() async {
Map<String, String> metadata = {'uuid': '123456'};
Uri uri = Uri(
scheme: 'https',
host: 'api.stripe.com',
path: '/v1/customers',
queryParameters: {
'description': 'Test Customer',
'metadata': metadata.entries.toList().toString()
});
var response = await client.post(
uri,
headers: {
'Authorization': 'Bearer ' + stripeTestKey,
},
);
print(response.body);
}
The error I am getting back from the endpoint is
> flutter: { "error": {
> "message": "Invalid object",
> "param": "metadata",
> "type": "invalid_request_error" } }
calling Stripe API requires a secret API key, and you shouldn't store and use the API key in your frontend application because it's not safe.
Instead you should make the API call from your backend where the API key can be securely stored.

GraphQL query to GitHub failing with HTTP 422 Unprocessable Entity

I am currently working on a simple GitHub GraphQL client in NodeJS.
Given that GitHub GraphQL API is accessible only with an access token, I set up an OAuth2 request to grab the access token and then tried to fire a simple GraphQL query.
OAuth2 flow gives me the token, but when I send the query, I get HTTP 422.
Here below simplified snippets from my own code:
Prepare the URL to display on UI side, to let user click it and perform login with GitHub
getGitHubAuthenticationURL(): string {
const searchParams = new URLSearchParams({
client_id,
state,
login,
scope,
});
return `https://github.com/login/oauth/authorize?${searchParams}`;
}
My ExpressJs server listening to GitHub OAuth2 responses
httpServer.get("/from-github/oauth-callback", async (req, res) => {
const {
query: { code, state },
} = req;
const accessToken = await requestGitHubAccessToken(code as string);
[...]
});
Requesting access token
async requestToken(code: string): Promise<string> {
const { data } = await axios.post(
"https://github.com/login/oauth/access_token",
{
client_id,
client_secret,
code
},
{
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
}
);
return data.access_token;
}
Firing simple graphql query
const data = await axios.post(
"https://graphql.github.com/graphql/proxy",
{ query: "{ viewer { login } }"},
{
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
}
);
Do you guys have any clue?
Perhaps I am doing something wrong with the OAuth2 flow? As in most of the examples I found on the web, a personal token is used for this purpose, generated on GitHub, but I would like to use OAuth2 instead.
Thanks in advance for any help, I really appreciate it!
EDIT
I changed the query from { query: "query { viewer { login } }"} to { query: "{ viewer { login } }"}, nonetheless, the issue is still present.
I finally found the solution:
Change the URL from https://graphql.github.com/graphql/proxy to https://api.github.com/graphql, see here
Add the following HTTP headers
"Content-Type": "application/json"
"Content-Length"
"User-Agent"
Hope this will help others out there.

Unable to POST using Angular 7 : Header Does not work

I'm currently building out an Angular 7 App, and trying to implement the following HTTP API Call Scenario:
Request for an Application Token:
https://(URL)/token
Request Type: POST
Headers:
Accept: application/json
Request Body: empty
I have a Service class in the Angular app and the code is as follows:
import { HttpClient } from '#angular/common/http';
import { HttpHeaders } from '#angular/common/http';
The requestToken function is implemented as follows:
requestToken() {
let headers = new HttpHeaders();
headers = headers.set('Accept', 'application/json');
return this.http.post(this.configUrl + '/token', headers);
}
The Service is then called in one of the components in the App:-
getToken() {
this.service.requestToken().subscribe( res => {
console.log(res);
}, error => {
console.log(error);
});
}
When I run the App, I get a 404 Not Found error in the console. I used Postman to make an API call, setting the 'Accept' header to 'application/json' and then specifying url as https://(URL)/token and I successfully get a response. But I'm unable to make it work via Angular.
Is there something else I need to do to set the header properly in Angular? Also, I have no way to check if CORS has been enabled on the API server as this is a third-party service which I'm trying to call.
Any help would be appreciated. Thanks
Solved the problem. Changed the POST call to the following:
requestToken() {
const httpHeaders = new HttpHeaders({
'Accept': 'application/json'
});
return this.http.post(this.configUrl + '/token', { body: ''}, { headers: httpHeaders });
}
Had to add an empty 'body' parameter