Failed to load firebase (redirected error) - javascript

I'm trying to learn ajax and I don't know back end language yet so I'm using firebase from google and I am running my code through localhost:8000 using python 2.7. I'm trying to GET/POST to this server:
https://ajax-practice-1f1b9.firebaseio.com/
If you can't access it, my JSON looks like this:
[
{
"id": 1,
"name" : "Will",
"drink": "American with creme"
},
{
"id": 2,
"name": "Donat",
"drink": "Vanilla Macchiato"
}
]
here's my HTML and javascript
$(function() {
$.ajax({
type: 'GET',
url: 'https://ajax-practice-1f1b9.firebaseio.com',
success: function(data) {
console.log(data);
}
});
});
<!doctype HTML>
<html>
<head>
<meta charset="utf-8">
<title>AJAX jQuery course</title>
<!-- latest bootstrap css -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
<h1>JQuery Ajax Tutorial</h1>
<h2>Coffee Order</h2>
<ulid="orders"></ul>
<p>name: <input type="text" id="name"></p>
<p>drink: <input type="text" id="drink"></p>
<button id="add-order">Add</button>
<!-- <script src="https://www.gstatic.com/firebasejs/5.3.1/firebase.js"></script> -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="index.js"></script>
</body>
</html>
I get this error on the console:
Failed to load https://console.firebase.google.com/project/ajax-practice-1f1b9/database/data/: Redirect from 'https://console.firebase.google.com/project/ajax-practice-1f1b9/database/data/' to 'https://accounts.google.com/ServiceLogin?passive=1209600&osid=1&continue=https://console.firebase.google.com/project/ajax-practice-1f1b9/database/data/&followup=https://console.firebase.google.com/project/ajax-practice-1f1b9/database/data/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I did something similar using axios and ReactJs a while back and it worked without problems.

The URL https://ajax-practice-1f1b9.firebaseio.com will try to load the database in the Firebase Database console. You are probably trying to get the data through Firebase's REST API, which requires that the URL ends in .json.
So to get the JSON for that location, use https://ajax-practice-1f1b9.firebaseio.com/.json.

Related

Google Analytics API JS quickstart example not working

I am trying to make a functional connection to GA API according to the official docs - https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/web-js. I did everything needed to set it up however the solution is not working. The weird thing is that the button for the authentication is loaded and its working up until the point where I select the google account to login with. After that however loading appears and the auth window gets closed. There is no error in the console, nothing happens at all.
I use it on localhost currently but I've also tried it on a server with the same result. After selecting the account, every next attempt doesn't even require choosing the account so the window just opens, loading appears and closes again without anything happening.
screenshot
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello Analytics Reporting API V4</title>
<meta name="google-signin-client_id" content="<CLIENT-ID>">
<meta name="google-signin-scope" content="https://www.googleapis.com/auth/analytics.readonly">
</head>
<body>
<h1>Hello Analytics Reporting API V4</h1>
<!-- The API response will be printed here. -->
<textarea cols="80" rows="20" id="query-output"></textarea>
<!-- The Sign-in button. This will run `queryReports()` on success. -->
<p class="g-signin2" data-onsuccess="queryReports"></p>
<script>
const VIEW_ID = '<VIEW-ID>';
// Query the API and print the results to the page.
function queryReports() {
gapi.client.request({
path: '/v4/reports:batchGet',
root: 'https://analyticsreporting.googleapis.com/',
method: 'POST',
body: {
reportRequests: [
{
viewId: VIEW_ID,
dateRanges: [
{
startDate: '7daysAgo',
endDate: 'today'
}
],
metrics: [
{
expression: 'ga:sessions'
}
]
}
]
}
}).then(displayResults, console.error.bind(console));
}
function displayResults(response) {
var formattedJson = JSON.stringify(response.result, null, 2);
document.getElementById('query-output').value = formattedJson;
}
</script>
<!-- Load the JavaScript API client and Sign-in library. -->
<script src="https://apis.google.com/js/client:platform.js"></script>
</body>
</html>
Is there something wrong in the code which I missed?

JavaScript + firebase. How can I implement the request using fetch for farebase, so to delete item in farebase [duplicate]

I'm trying to learn ajax and I don't know back end language yet so I'm using firebase from google and I am running my code through localhost:8000 using python 2.7. I'm trying to GET/POST to this server:
https://ajax-practice-1f1b9.firebaseio.com/
If you can't access it, my JSON looks like this:
[
{
"id": 1,
"name" : "Will",
"drink": "American with creme"
},
{
"id": 2,
"name": "Donat",
"drink": "Vanilla Macchiato"
}
]
here's my HTML and javascript
$(function() {
$.ajax({
type: 'GET',
url: 'https://ajax-practice-1f1b9.firebaseio.com',
success: function(data) {
console.log(data);
}
});
});
<!doctype HTML>
<html>
<head>
<meta charset="utf-8">
<title>AJAX jQuery course</title>
<!-- latest bootstrap css -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
<h1>JQuery Ajax Tutorial</h1>
<h2>Coffee Order</h2>
<ulid="orders"></ul>
<p>name: <input type="text" id="name"></p>
<p>drink: <input type="text" id="drink"></p>
<button id="add-order">Add</button>
<!-- <script src="https://www.gstatic.com/firebasejs/5.3.1/firebase.js"></script> -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="index.js"></script>
</body>
</html>
I get this error on the console:
Failed to load https://console.firebase.google.com/project/ajax-practice-1f1b9/database/data/: Redirect from 'https://console.firebase.google.com/project/ajax-practice-1f1b9/database/data/' to 'https://accounts.google.com/ServiceLogin?passive=1209600&osid=1&continue=https://console.firebase.google.com/project/ajax-practice-1f1b9/database/data/&followup=https://console.firebase.google.com/project/ajax-practice-1f1b9/database/data/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I did something similar using axios and ReactJs a while back and it worked without problems.
The URL https://ajax-practice-1f1b9.firebaseio.com will try to load the database in the Firebase Database console. You are probably trying to get the data through Firebase's REST API, which requires that the URL ends in .json.
So to get the JSON for that location, use https://ajax-practice-1f1b9.firebaseio.com/.json.

CORS error when using elasticsearch.js

I am trying to test an index from my local machine. I created a simple HTML page with a query box that sends the query to ES using the elasticsearch.js client. Both the index and the browser are on my desktop, so there shouldn't be a cross origin problem, but I keep getting an error that states:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:9200/portal/book/_search?q=title%3Ahistoire. This can be fixed by moving the resource to the same domain or enabling CORS.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:9200/. This can be fixed by moving the resource to the same domain or enabling CORS.
I tried enabling CORS, but get the same error. Here are the index's settings:
{
"portal": {
"settings": {
"index": {
"creation_date": "1421788614558",
"uuid": "jg-iHjnSTDGHODY0_x4Ysw",
"number_of_replicas": "1",
"http": {
"cors": {
"enabled": "true",
"allow-origin": "/(http://)?localhost(:[0-9]+)?/"
}
},
"number_of_shards": "5",
"version": {
"created": "1040299"
}
}
}
}
}
index.html
<!DOCTYPE html >
<html ng-app="portal">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/elasticsearch/elasticsearch.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
</head>
<body ng-controller="SearchCtrl">
<div class="container-fluid">
<div class="row-fluid">
<span class="span3">
<input class="input-block-level" ng-model="queryTerm" type="text">
</span>
<button ng-click="search()" class="btn" type="button">Search</button>
</div>
<div class="row-fluid">
Found {{ results.hits.total }}
<div class="span4">
<li ng-repeat="doc in results.hits.hits">
{{ doc._source.title }}
</li>
</div>
</div>
</div>
</body>
</html>
app.js
angular.module('portal', [
'controllers',
]);
var client = new elasticsearch.Client({
host: 'http://localhost:9200',
apiVersion: '1.3',
});
controller.js
angular.module('controllers', []).controller('SearchCtrl',
function($scope) {
$scope.search = function(query) {
$scope.results = client.search({
index: 'portal',
type: 'book',
q: 'title:' + $scope.queryTerm
}, function (error, response) {console.log('could not execute query!')}
);
};
}
);
Add following line to your config yml file
http.cors.enabled : true
http.cors.allow-origin: "*"
http.cors.allow-methods: OPTIONS, HEAD, GET, POST, PUT, DELETE
http.cors.allow-headers: X-Requested-With,X-Auth-Token,Content-Type,Content-Length
http.cors.allow-credentials: true
and kill elastic search java process on unix based system like is demonstrated on this topic response https://stackoverflow.com/a/41644614/11079315
I don't know why you are getting a cross domain error to begin with. Are you opening your front end as file://.... ? Totally random guess and not sure it matters. If you are and want to run your UI through a web server, you can open a terminal, cd into that dir and run 'python -m SimpleHTTPServer 7000'. Now your UI is running on localhost:7000.
For CORS settings, see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/modules-http.html and, if you are using Chrome, http://www.williamjohnbert.com/2013/06/allow-cors-with-localhost-in-chrome/ might help.
In your config you should at least set 'http.cors.enabled: true' and 'http.cors.allow-credentials: true'. The other defaults should be sensible. You may also want to modify the 'http.cors.max-age' setting in case old settings are cached.
Use the js console, net tab in your browser to see what headers you are getting back.

Chrome Extension (sandboxed) with Angularjs

it's days I'm trying to figure out how to make a chrome extension I'm building working...with AngularJS.
Problem is that I cannot successfully access remote resources; as long as I didn't use angular, my way to communicate between the main html and the sandbox was with a pub/sub javascript I found on the web pkg.js and in this way I could call external urls in the main.js and pass retrieved data back to subscribed javascripts.
I have heavily simplified my code so that you can better understand the architecture. Here are some test resources that works perfectly apart from the fact...that angular does not work :/
My manifest has the following relevant parts:
{
...
"background": {
"scripts": ["new/ext/background.js"],
"persistent": false
},
"permissions": [
"tabs",
"http://*.mysite.com/*"
],
"sandbox": {
"pages": [ "new/testmain.html" ]
},
"content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'"
}
My background.js is very simple: it just creates a tab and calls an html which will host the angular code:
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.tabs.create({'url': chrome.extension.getURL('/new/main.html')}, function (tab) { });
});
The main.html is, too, pretty easy: just some script includes and the iframe:
<!doctype html>
<html>
<head>
<title>Testing angular</title>
<script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js"></script>
<!-- custom scripts -->
<script type="text/javascript" src="/lib/pkg.js"></script>
</head>
<body style="height: 100%">
<h1>Iframe below</h1>
<iframe id="iframe" src="testmain.html" width="100%" height="100%" frameborder="none"></iframe>
<script type="text/javascript" src="testmain.js"></script>
</body>
</html>
The testmain.js just subscribes to an event and, in case receives it, it publishes dummy data:
iframe = document.getElementById("iframe");
$.pkg.init(iframe.contentWindow);
$.pkg.listen("items", function () {
console.log("[testmain.js] received items message");
items = [
{ name:"foo", age: 12 },
{ name:"bar", age: 11 },
{ name:"mickey", age: 15},
{ name: "donald", age: 27}
];
$.pkg.send("response", [items]);
console.log("[testmain.js] sent response");
});
Now let's come to testmain.html:
<!DOCTYPE html>
<html data-ng-app="App" data-ng-csp>
<head>
<title></title>
</head>
<body ng-controller="TodoCtrl">
<div ng-repeat="item in testitems">
<ul>
<li>{{item.name}}</li>
</ul>
</div>
<script type='text/javascript' src="lib/jquery.min.js"></script>
<script type="text/javascript" src="lib/angular.min.js"></script>
<script src="/lib/pkg.js"></script>
<script src="app/testapp.js"></script>
</body>
</html>
And, finally, here is the testapp.js:
var App = angular.module('App', []);
App.controller('TodoCtrl', function($scope) {
//test
$.pkg.init(window.top);
$.pkg.send("items");
console.log("[testapp.js] sent message items");
$.pkg.listen("response", function(res){
console.log("[testapp.js] received " + res.length + " items");
$scope.testitems = res;
for (i = 0; i < $scope.testitems.length; i++) {
console.log("[testapp.js] testitem: " + $scope.testitems[i].name);
}
});
});
The controller just inits the communication with destination = html containing the iframe. It then sends a message requesting for data which is then sent back (listens).
If I try from the console to run any manual command to get the $scope variable, no success at all:
document.getElementById('iframe')
Sandbox access violation: Blocked a frame at "chrome-extension://jcnppfndabbcgbdcnjncnoddmhmkmmbb" from accessing a frame at "chrome-extension://jcnppfndabbcgbdcnjncnoddmhmkmmbb". The frame being accessed is sandboxed and lacks the "allow-same-origin" flag.
Sandbox access violation: Blocked a frame at "chrome-extension://jcnppfndabbcgbdcnjncnoddmhmkmmbb" from accessing a frame at "chrome-extension://jcnppfndabbcgbdcnjncnoddmhmkmmbb". The frame being accessed is sandboxed and lacks the "allow-same-origin" flag.
Sandbox access violation: Blocked a frame at "chrome-extension://jcnppfndabbcgbdcnjncnoddmhmkmmbb" from accessing a frame at "chrome-extension://jcnppfndabbcgbdcnjncnoddmhmkmmbb". The frame being accessed is sandboxed and lacks the "allow-same-origin" flag.
<iframe id="iframe" src="testmain.html" width="100%" height="100%" frameborder="none"></iframe>
This is what happens in the console:
[testapp.js] sent message items testapp.js:8
[testmain.js] received items message testmain.js:5
[testmain.js] sent response testmain.js:13
[testapp.js] received 4 items testapp.js:10
[testapp.js] testitem: pippo testapp.js:13
[testapp.js] testitem: pluto testapp.js:13
[testapp.js] testitem: paperino testapp.js:13
[testapp.js] testitem: minnie testapp.js:13
as you may notice, communication DO occur, $scope.testitems variable is set correctly. BUT nothing is rendered on the iframe :(
Can anyone help me figure out how to come out of all of this?
Btw, I was in a some way forced to do so - the first version which was on plnkr gladly used the $http inside the controller, but this appears to be prohibited in chrome extensions...
I also tried to use amplifyjs but didn't come to out to make the communication work between an iframe and its container.
Thanks a lot!

Typeahead.js prefetch option not working

I am unable to get the prefetch option to work in typeahead.js. Local data works fine. Answers to previously posted questions suggest that caching could be an issue, but I have set the ttl to 0 and am testing in private browsing mode in Firefox and Chrome. What am I missing?
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://twitter.github.com/typeahead.js/releases/latest/typeahead.css">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://twitter.github.com/typeahead.js/releases/latest/typeahead.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function(){
$('#searchText').typeahead([
{
name: 'terms',
//local: ["United States", "Canada"],
prefetch: 'http://twitter.github.io/typeahead.js/data/countries.json',
ttl: 0
}
]);
});
</script>
<body>
<div class="container">
<input class="typeahead" type="text" id="searchText">
</div>
</body>
</html>
You should always check the console (Firebug / Chrome dev tools) when something is "not working", it's your best friend when working with JS.
In this case, it's not that prefetch is not working. But Github doesn't allow you to fetch that json from different domain. If you check your console, you will see this error:
XMLHttpRequest cannot load http://twitter.github.io/typeahead.js/data/countries.json. Origin http://yourdomain is not allowed by Access-Control-Allow-Origin.
So if you want to get this example working locally, you should download that JSON file and set it up locally, then change the URL a bit like:
$(document).ready(function(){
$('#searchText').typeahead({
name: 'terms',
prefetch: '/data/countries.json', // go to http//yourdomain/data/countries to make sure the path is correct
ttl: 0
});
});
Hope it helps.

Categories

Resources