I had embeded an HTML in a webview of iOS. I want to send a request of ajax with vue-resouce framework. The request is ok, but why in the iOS vue-resouce get request cannot accept the callback?
var vm = new Vue({
el:'#check',
data:{
msg:'Hello World!',
url:'http://localhost:8080/v1/user/check/'
},
methods:{
get:function(token){
alert(token)
var realUrl = this.url + token
this.$http.get(realUrl).then(function(response){
alert('1')}
).then(function(response){
alert(response);
alert('1')
});
}
}
});
function getToken() {
var token = bridge.call("getToken")
alert(token)
vm.get(token);
}
Related
I want to ask about how to send an event using firebase & electron.js. A friend of mine has a problem when using firebase analytics and electron that it seems the electron doesn't send any event to the debugger console. When I see the network it seems the function doesn't send anything but the text successfully go in console. can someone help me to figure it? any workaround way will do, since he said he try to implement the solution in this topic
firebase-analytics-log-event-not-working-in-production-build-of-electron
electron-google-analytics
this is the error I got when Try to use A solution in Point 2
For information, my friend used this for the boiler plate electron-react-boilerplate
The solution above still failed. Can someone help me to solve this?
EDIT 1:
As you can see in the image above, the first image is my friend's code when you run it, it will give a very basic example like in the image 2 with a button to send an event.
ah just for information He used this firebase package :
https://www.npmjs.com/package/firebase
You can intercept HTTP protocol and handle your static content though the provided methods, it would allow you to use http:// protocol for the content URLs. What should make Firebase Analytics work as provided in the first question.
References
Protocol interception documentation.
Example
This is an example of how you can serve local app as loaded by HTTP protocol and simulate regular browser work to use http protocol with bundled web application. This will allow you to add Firebase Analytics. It supports poorly HTTP data upload, but you can do it on your own depending on the goals.
index.js
const {app, BrowserWindow, protocol} = require('electron')
const http = require('http')
const {createReadStream, promises: fs} = require('fs')
const path = require('path')
const {PassThrough} = require('stream')
const mime = require('mime')
const MY_HOST = 'somehostname.example'
app.whenReady()
.then(async () => {
await protocol.interceptStreamProtocol('http', (request, callback) => {
const url = new URL(request.url)
const {hostname} = url
const isLocal = hostname === MY_HOST
if (isLocal) {
serveLocalSite({...request, url}, callback)
}
else {
serveRegularSite({...request, url}, callback)
}
})
const win = new BrowserWindow()
win.loadURL(`http://${MY_HOST}/index.html`)
})
.catch((error) => {
console.error(error)
app.exit(1)
})
async function serveLocalSite(request, callback) {
try {
const {pathname} = request.url
const filepath = path.join(__dirname, path.resolve('/', pathname))
const stat = await fs.stat(filepath)
if (stat.isFile() !== true) {
throw new Error('Not a file')
}
callback(
createResponse(
200,
{
'content-type': mime.getType(path.extname(pathname)),
'content-length': stat.size,
},
createReadStream(filepath)
)
)
}
catch (err) {
callback(
errorResponse(err)
)
}
}
function serveRegularSite(request, callback) {
try {
console.log(request)
const req = http.request({
url: request.url,
host: request.url.host,
port: request.url.port,
method: request.method,
headers: request.headers,
})
if (req.uploadData) {
req.write(request.uploadData.bytes)
}
req.on('error', (error) => {
callback(
errorResponse(error)
)
})
req.on('response', (res) => {
console.log(res.statusCode, res.headers)
callback(
createResponse(
res.statusCode,
res.headers,
res,
)
)
})
req.end()
}
catch (err) {
callback(
errorResponse(err)
)
}
}
function toStream(body) {
const stream = new PassThrough()
stream.write(body)
stream.end()
return stream
}
function errorResponse(error) {
return createResponse(
500,
{
'content-type': 'text/plain;charset=utf8',
},
error.stack
)
}
function createResponse(statusCode, headers, body) {
if ('content-length' in headers === false) {
headers['content-length'] = Buffer.byteLength(body)
}
return {
statusCode,
headers,
data: typeof body === 'object' ? body : toStream(body),
}
}
MY_HOST is any non-existent host (like something.example) or host that is controlled by admin (in my case it could be electron-app.rumk.in). This host will serve as replacement for localhost.
index.html
<html>
<body>
Hello
</body>
</html>
How can I generate Google oauth2 Access token in Erlang.
I can generate the token in NodejS i. I need it in Erlang as all my rest api code is in Erlang.
Blockquote
var {google} = require('googleapis');
var MESSAGING_SCOPE = "https://www.googleapis.com/auth/firebase.messaging";
var SCOPES = [MESSAGING_SCOPE];
var http = require('http')
function getAccessToken(){
return new Promise(function(resolve, reject){
var key = require("./ServiceAccountKey.json");
var jwtClient = new google.auth.JWT(
key.client_email,
null,
key.private_key,
SCOPES,
null
);
jwtClient.authorize(function(err, tokens){
if(err){
reject(err);
return;
}
resolve(tokens.access_token+" : "+tokens.expiry_date);
});
});
}
var server = http.createServer(function(req, res){
getAccessToken().then(function(access_token){
res.end(access_token);
});
});
server.listen(3000, function(){
console.log("Server started");
});
Tried to generate the Code
URL="https://accounts.google.com/o/oauth2/auth",
Scope="https://www.googleapis.com/auth/firebase.messaging",
GetURL=URL++"?client_id="++ClientId++"&redirect_uri=com.example.app:/oauth2redirect&scope="++Scope++"&response_type=code",
Response = httpc:request(URL),
Response.
Return bad Request
In your code, you're creating a URL with all required query parameters and putting it in the variable GetURL, but then you pass URL, which is just the base URL, to httpc:request. Try passing GetURL instead, and see if that gets you further:
Response = httpc:request(GetURL),
I am trying to use service worker with PreloadJS. I have cached the images required and then loading them using the caches.match() function.
When I try to load the image with jquery it works fine, but on loading with preloadJS it gives the following error
The FetchEvent for "someurl" resulted in a network error response: an "opaque" response was used for a request whose type is not no-cors
Although if I load any other image that isn't cached, PreloadJS loads that image properly. The problem is occuring only when I use caches.match.
What might be the reason for this ?
Load Image using preloadjs
var preload = new createjs.LoadQueue({ crossOrigin: "Anonymous" });
function loadImageUsingPreload() {
preload.on('complete', completed);
preload.loadFile({ id: 'someid', src: 'someurl', crossOrigin: true })
};
function completed() {
var image = preload.getResult("shd");
document.body.append(image);
};
Load Image using jquery
function loadImageUsingJquery() {
jQuery("#image").attr('src', 'someurl');
};
Service Worker fetch event
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
if (!response) {
console.log('fetching...' + event.request.url);
return fetch(event.request);
};
console.log("response", response);
return response;
}));
});
The response object when I load using PreloadJS or jQuery:
Response {type: "opaque", url: "", redirected: false, status: 0, ok: false, …}
Found out the mistake ,
Actually during cache.put I was modifying the request object's mode to 'no-cors' if the origin were not the same.
Now during a fetch event, the event's request object had property 'cors' because it was a cross-origin request.
This difference of value of mode was causing the fetch error.
Service worker install event:
var request = new Request(value);
var url = new URL(request.url);
if (url.origin != location.origin) {
request = new Request(value, { mode: 'no-cors' });
}
return fetch(request).then(function(response) {
var cachedCopy = response.clone();
return cache.put(request, cachedCopy);
});
I changed it to :
var request = new Request(value);
var url = new URL(request.url);
return fetch(request).then(function(response) {
var cachedCopy = response.clone();
return cache.put(request, cachedCopy);
});
I have to use the first method for saving cdn's because second method is not working for them and vice-versa for my images hosted on cloudfront .
I will post the reason when I find why this is happening.
I am using ionic Framework. i have multiple HTTP service which is working fine. Now problem is that whenever i get response of any http call. i can't proceed further.
Can we run HTTP Service as a background process. So my application continues works without waiting for result.
here is my code
articleService.getArticles().then(function() {
},function(err){
});
and sercvice code
$http({
url: "http://myservice.com",
data: { user_id: 1 },
method: 'POST',
withCredentials: true,
}).success(function (data) {
deferred.resolve(data);
}).error(function (err) {
deferred.resolve(0);
})
return deferred.promise;
}
Any idea? I need a solution in ionic framework which will work both for ios and andriod?
Thanks
try to use html5 web workers what u need to do is multithreading and because that javascript is single threading environment you have to web workers
https://html.spec.whatwg.org/multipage/workers.html
Look at this plunker this what you need and it is all angularjs so will work with ionic.
var app = angular.module('angularjs-starter', []);
app.config(function($routeProvider) {
$routeProvider.
when('/', {controller:'StartCtrl', templateUrl:'start.html'}).
when('/main', {controller:'MainCtrl', templateUrl:'main.html'}).
otherwise({redirectTo:'/'});
});
app.controller('MainCtrl', function($scope, Poller) {
$scope.name = 'World';
$scope.data = Poller.data;
});
app.controller('StartCtrl',function(){});
app.run(function(Poller) {});
app.factory('Poller', function($http, $timeout) {
var data = { response: {}, calls: 0 };
var poller = function() {
$http.get('data.json').then(function(r) {
data.response = r.data;
data.calls++;
$timeout(poller, 1000);
});
};
poller();
return {
data: data
};
});
Maybe i misunderstand your question but i think your service code is wrong.
Try something like this
myApp.factory('articleService', function($http) {
return {
getArticles: function getArticles() {
return $http({...}); // $http returns a promise, so you dont need your own defer.promise
}
}
});
//usage
//first: send or get data async
articleService.getArticles().then(function(resp){
alert('called second');
...
});
// second: do something else, this will not wait for your response
alert('called first');
I've looked at multiple solutions to this problem but nothing's working to fix my problem.
I'm using ASP.NET MVC 4.5.
Here are my steps:
Use ajax call in page to upload file.
Within same function that generates ajax call run an ajax call to refresh the page to include the uploaded file, after ajax call is finished.
I'm using this as the first call (to upload) (compliments of another Stack Overflow user):
function uploadFiles() {
document.getElementById('fileupload').onsubmit = function () {
var formdata = new FormData(); //FormData object
var fileInput = document.getElementById('uploadfilenames');
//Iterating through each files selected in fileInput
for (i = 0; i < fileInput.files.length; i++) {
//Appending each file to FormData object
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Dashboard/UploadFiles');
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
//alert(xhr.responseText);
}
}
return false;
}
reloadMain();
}
The reloadMain() function is:
function reloadMain() {
$.ajax({
url: '/Dashboard/ThumbList/' + currentPath,
type: "GET",
timeout: 5000,
success: function (msg) {
$("#thumb-list").html(msg)
},
error: displayError("Unable to get file listing")
});
}
I have noticed this:
The 'refresh' doesn't include the uploaded file information in the response
IE11 and Chrome act differently.
It seems that the problem is that the controller/system doesn't complete the file operations soon enough (I saw a "denied access...file in use" error when using Chrome.
So, it would seem that the refresh ajax call needs to wait until the file system completes its work.
Would you agree? If so, how can I make this work?
You can either set your XMLHttpRequest async to false:
xhr.open('POST', '/Dashboard/UploadFiles', false);
Or you can call your refresh function in callback:
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Dashboard/UploadFiles');
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
reloadMain(); //Only refresh after the file post get a 200 response
}
}