Unexpected token G in JSON at position 0 with Google Analytics - google-analytics

I am trying to use the Measurement Protocol from Google Analytics in my working Angular 5 project. I put the Google Analytics Universal code in index.html and I am making http calls to the service like this
index.html
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-XXXXXXXX-Y', {
'cookieDomain': 'none'
});
// console.log(window.dataLayer);
</script>
Service launching http calls
import { Injectable } from '#angular/core';
import { HttpClient, HttpParams, HttpHeaders } from '#angular/common/http';
import { DataService } from './Data.service';
#Injectable()
export class AnalyticsService {
private anUID = 'UA-XXXXXXXX-Y';
private analyticsURL = 'https://www.google-analytics.com/collect?';
constructor(private http: HttpClient, private datos: DataService) { }
public pageViewLista(): void {
this.http.get(
this.setScreenViewUrl(
encodeURI('Lista de empresas'))).subscribe((data) => {
console.log('Received data from GAnalytics: ' + JSON.stringify(data));
}
);
}
protected setScreenViewUrl (pantalla: string): string {
const constructUrl = `${this.analyticsURL}v=1&t=screenview&tid=${this.anUID}&cid=${this.datos.id}&an=${this.datos.app}&dt=${pantalla}&cd=${pantalla}`;
return constructUrl;
}
}
The problem is what Google returns an strange error and I dont know what it means nor the reason of this error. Am I doing a bad implementation?
Error from Google:
ERROR
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "https://www.google-analytics.com/collect?v=1&t=...", ok: false, …}
error : {error: SyntaxError: Unexpected token G in JSON at position 0 at JSON.parse () at XMLHttp…, text: "GIF89a�����,D;"}
It seems like if the server was tryings to JSON parse a GIF image. Cant find anything in the documentation and Google shows no information.
Thanks a lot for your help.

The Google Analytics endpoint for data collection returns a transparent gif file (and it returns a 200 status for everything but server errors, so you can't use this to see if your data is actually tracked). A gif cannot be decoded as JSON.
If you want a JSON response you would need to use the endpoint for the GA debugger (google-analytics.com/debug/collect). That would give info if your payload is valid, but would not track the call.

Related

Ionic 6 Http Post shows unknown error in normalizedNames for capacitor project

I am calling my Wordpress REST JSON API in my Ionic Capacitor Project.
But i am getting the error shown in image below.
Ionic Capacitor HTTP Error
This is my code
const httpHeader = { // constant for http headers
headers : new HttpHeaders({
'Content-Type':'application/json',
'Access-Control-Allow-Origin': '*'
})
};
createComment(comment: Comment): Observable<any> {
return this.http.post('https://readymadecode.com/wp-json/wp/v2/comments/create,{
"post":4000,
"parent":"0",
"author_name":"chetan",
"author_email":"chetan#gmail.com",
"content":"nice good article"
},httpHeader).pipe(map(this.dataExtract),catchError(this.errorHandler));
}
private dataExtract(res: Response){ // This method extract data from the request response
const body = res;
return body || {};
}
private errorHandler(error: HttpErrorResponse){ // Method for error handler
console.error(error.error instanceof ErrorEvent?`Error message:
${error.error.message}`:`Error status: ${error.error.data.status} Body: ${error.error.message}`);
return throwError(`${error.error.message}`);
}
When i call the createComment function it shows error see in image above. I have tried enable CORS with cordova-plugins-whitelist but still it shows error.
But this api is working fine in postman. I am using this in postman.
URL: https://www.readymadecode.com/wp-json/wp/v2/comments/create
Method: POST
Body: {
"post":4000,
"parent":"0",
"author_name":"chetan",
"author_email":"chetan#gmail.com",
"content":"nice good article"
}
Please help how can i solve this error.
after try all the methods available on google, i able to solve this issue by simply removing the httpHeader from the api.
createComment(comment: Comment): Observable<any> {
return this.http.post('https://readymadecode.com/wp-json/wp/v2/comments/create,{
"post":4000,
"parent":"0",
"author_name":"chetan",
"author_email":"chetan#gmail.com",
"content":"nice good article"
},httpHeader).pipe(map(this.dataExtract),catchError(this.errorHandler));
}

Grab response message from .NET Core API with ky

I use ky package for sending HTTP requests to web api. Everything works except handling error messages.
Let me show you my source code:
// api method
[HttpPost("Test")]
public async Task<IActionResult> Test([FromBody] TestViewModel model)
{
if(model.Test)
{
return StatusCode(StatusCode.Status200OK, "Success message");
}
else
{
return StatusCode(StatusCodes.Status500InternalServerError, "Error message");
}
}
My aim is get and display Success message or Error message text on the frontend.
Client side:
//webclient.js
import ky from "ky";
export const webclient = ky.create({
prefixUrl: "http://localhost:62655/api",
});
Firing API call:
//testAPI.js
import { webclient } from '../../common/webclient';
const result = await webclient.post('Order/Test', { json: { ...model } }).json();
console.log(result);
If the status code is equal to 200 the message (Success message) show in console properly, but for 500 (or 400, or any else) console remains empty.
DevTools confirm that API returns 500 status code with message Error message so it's not an API problem.
The question is: how can I obtain an error message with ky?
The ky library doesn't seem very mature but I did find this issue thread which might help ~ https://github.com/sindresorhus/ky/issues/107#issuecomment-476048453
I would strongly suggest you just stick to vanilla fetch where you're in full control of handling the response text if required
const response = await fetch("http://localhost:62655/api/Order/Test", {
method: "POST",
headers: { "Content-type": "application/json" },
body: JSON.stringify({ ...model })
})
if (!response.ok) {
throw new Error(`${response.status}: ${await response.text()}`)
}
console.log(await response.json())

Angular 4 and ASP.Net MVC 5 : returns an Empty JSON in response

after merging angular app with asp.net MVC calling API from angular returns an empty JSON.
The angular and asp.net are in the same domain.
If I call the API With PostMan, I have a JSON with the result. but if I call it in the angular app my JSON result is empty.
Are there any tips for communicating angular app with asp.net MVC after merging and serving in the same domain?
Update 1:
The code that used to calling Webservice:
getSheets(): Observable<Sheet[]> {
return this.http.get(this.config.apiUrl + '/api/SheetsRelationAPI',
this.jwt())
.map(this.extractData)
.do(data => console.log('SheetsData:', data)) // debug
.catch(this.handleError);
}
/**
* Handle HTTP error
*/
private handleError(error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
const errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
// private helper methods
private jwt() {
// create authorization header with jwt token
const currentUser = JSON.parse(atob(this.cookie.getCookie('currentUser')));
if (currentUser && currentUser.access_token) {
const headers = new Headers({ 'Authorization': 'Bearer ' + currentUser.access_token},
);
return new RequestOptions({ headers: headers });
}
}
private extractData(res: Response) {
const body = res.json();
return body || [];
}
Update 2:
I notice that my API if I called it from outside domain it respond 2 times:
inspecting network with google chrome inspect element:
the first response is "zone.js" initiator and the second response is an "other" initiator
If I call the API from inside of the Domain I just have a response from "zone.js" initiator and it returns an empty JSON.
Update 3
export class OtherComponent implements OnInit {
sheets: Sheet[] = [];
errorMessage: string;
constructor(private httpService: HttpService) {
// this.sheets = this.ichartHttp.getSheets();
// console.log(this.sheets);
}
getSheets() {
this.httpService.getSheets()
.subscribe(
sheets => this.sheets = sheets,
error => this.errorMessage = <any>error
);
}
ngOnInit() {
this.getSheets();
}
}
The Problem is with my Authentication methods,
I use two types of authentication, MVC and WebAPI they conflict if I send a request to API under the same Domain.
So my Answer is: Your Angular Code looks good, take a look at your middleware project

Chaining RxJS Observables with interval

my first question to the community out here!
i'm working on an app which does communicates to the API in the following way
step1: create request options, add request payload --> Post request to API
API responds with a request ID
Step2: update request options, send request ID as payload --> post request to API
final response: response.json
Now the final response can take a bit of time, depending on the data requested.
this can take from anywhere between 4 to 20 seconds on an average.
How do i chain these requests using observables, i've tried using switchmap and failed (as below) but not sure how do i add a interval?
Is polling every 4 second and unsubscribing on response a viable solution? how's this done in the above context?
Edit1:
End goal: i'm new to angular and learning observables, and i'm looking to understand what is the best way forward.. does chaining observable help in this context ? i.e after the initial response have some sort of interval and use flatMap
OR use polling with interval to check if report is ready.
Here's what i have so far
export class reportDataService {
constructor(private _http: Http) { }
headers: Headers;
requestoptions: RequestOptions;
payload: any;
currentMethod: string;
theCommonBits() {
//create the post request options
// headers, username, endpoint
this.requestoptions = new RequestOptions({
method: RequestMethod.Post,
url: url,
headers: newheaders,
body: JSON.stringify(this.payload)
})
return this.requestoptions;
}
// report data service
reportService(payload: any, method: string): Observable<any> {
this.payload = payload;
this.currentMethod = method;
this.theCommonBits();
// fetch data
return this._http.request(new Request(this.requestoptions))
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || {};
}
private handleError(error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
in my component
fetchData() {
this._reportService.reportService(this.payload, this.Method)
.switchMap(reportid => {
return this._reportService.reportService(reportid, this.newMethod)
}).subscribe(
data => {
this.finalData = data;
console.info('observable', this.finalData)
},
error => {
//console.error("Error fetcing data!");
return Observable.throw(error);
}
);
}
What about using Promise in your service instead of Observable, and the .then() method in the component. You can link as much .then() as you want to link actions between them.

How to recognise an existing Google OAuth authentication made via Firebase and perform a Google Directory API request in Angular 2?

I want to use my existing authentication and be able to use that same authentication to perform a get request to the Google Directory API. Here's my current code:
login() {
this.firebaseRef = new Firebase('https://xxx.firebaseio.com');
this.firebaseRef.authWithOAuthPopup("google", (error, authData) => {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
}, {
scope: "https://www.googleapis.com/auth/admin.directory.user.readonly"
});
}
getData() {
// TO-DO
// Recognise existing OAuth and perform a GET request to
// https://www.googleapis.com/admin/directory/v1/users?domain=nunoarruda.com
}
You could leverage the getAuth method on the firebaseRef instance. Something like that:
getData() {
var authData = this.firebaseRef.getData();
var provider = authData.provider;
// In your case provider contains "google"
}
See this documentation: https://www.firebase.com/docs/web/api/firebase/getauth.html.
I've found the solution. I need to use the current access token in the http request headers for the GET request.
import {Http, Headers} from 'angular2/http';
getData() {
// get access token
let authData = this.firebaseRef.getAuth();
let oauthToken = authData.google.accessToken;
console.log(oauthToken);
// set authorization on request headers
let headers = new Headers();
headers.append('Authorization', 'Bearer ' + oauthToken);
// api request
this.http.get('https://www.googleapis.com/admin/directory/v1/users?domain=nunoarruda.com',{headers: headers}).subscribe((res) => {
console.log(res.json());
});
}

Resources