How fix or disable proxy in phonegap? - angularjs

When my app do POST request its work. look like
http://192.168.0.165:3000/proxy/http%3A%2F%2Fhomestead.app%2Fapi%2Fv1%2Fuser%2F
But when I do next request with GET that don't work.
I think it because phonegap lost what I send in my params. How I can fix it or disable proxy in phonegap?

Add this in your index.html file
(function() {
var xhr = {};
xhr.open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url) {
console.log(url);
if(url.indexOf('/proxy/') == 0){
url = window.decodeURIComponent(url.substr(7));
}
xhr.open.apply(this, arguments);
};
})(window);
If you begin to face the "Access-Control-Allow-Origin" problem use this extension for chrome (modheader) and add a response like this:
Access-Control-Allow-Origin:http://yourip:3000
If you are making multiple requests and wish the session be shared between them then add another response like this:
Access-Control-Allow-Credentials: true

Related

$http.get success method not called

I am new to AngularJS & NodeJS. I am trying to get a API response from NodeJS and display it in angular. I am using $http to make API call. Below is my nodeJS code.
var express = require('express');
var app = express();
app.get('/employees',function(req,res)
{
console.log("Test Output :");
res.status(200).send('Hello User');
});
app.listen(8080);
Below is my angular code
var myapp = angular.module('myapp',[]).controller('myappController', ['$scope','$http',function ($scope,$http){
$http.get('http://127.0.0.1:8080/employees')
.then(function(response)
{
window.alert("Success");
$scope.emdata=response.data;
},function(errorresponse)
{
window.alert("Error");
$scope.emdata=errorresponse.status;
});
}]);
I am using expression {{emdata}} in HTML page. When I open the HTML page I can see the console output "Test Output " in NodeJS terminal which means the API is getting called but I dont see "Hello User" in HTML page. It looks like the success function in $http.get is not getting called and only the error function is getting called. So I see an alert window with "Error" whenever I open the HTML page and response status as -1 in the place of {{emdata}}.
When I tried making the API call using Postman I get correct response with status 200. So I am wondering what is wrong?
Check headers, i.e. what format is accepted by $http request and the format of the response (JSON, plain text, etc).
Fix value in
$httpProvider.defaults.headers.common
or set needed one in
$httpProvider.defaults.headers.get = { ... };
or just use
var requestParams = {
method: 'GET',
url: '...',
headers: {
...
}
};
$http(requestParams).then(...);
Take a look at Setting HTTP Headers in official manual for more details.

How do you pass in HTTP headers to make a request from an API?

Using Angular, I'm trying to pass in HTTP headers with the request, “App-Id” and “App-Key” to get data from this API.
I tried setting the headers like this:
$http.defaults.headers.common["App-Id"] = '5a3d8b8d';
$http.defaults.headers.common["App-Key"] = '738e9aca62e7465446b7be8fe4219ffa';
but I got a Response for preflight is invalid error.
http://jsfiddle.net/9Ymvt/4573/
Adding Headers to an $http Request on a Per Request Basis
To add headers to a $http request on a per request basis, add them to the headers property of the $http config object.
var xheaders = {};
xheaders["App-Id"] = '5a3d8b8d';
xheaders["App-Key"] = '738e9aca62e7465446b7be8fe4219ffa';
var xurl = 'https://uk.bookingbug.com/api/v1';
var configObj = { method: 'GET',
url: xurl,
headers: xheaders
};
$http(configObj)
.then(function onFulfilled(response) {
console.log(response);
vm.headers = response.config.headers;
vm.data = response.data
}).catch( function onRejection(errorResponse) {
console.log("Error: ", errorResponse.status);
console.log(errorResponse);
vm.error = errorResponse;
})
;
The code was getting pre-flight errors because it was using the incorrect URL. The correct base URL is https://uk.bookingbug.com/api/v1 which supports App-Id headers and CORS.
The DEMO on JSFiddle.
I do not think this is a complete answer to your question, but here is what I have in my project:
var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider) {
// code for routes
});
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
This solves my problem with CORS. If you want to do another type of header, you probably can find your answer here.
Preflight errors are related to CORS. You might want to look at rack-cors to enable cross-site api calls via javascript. There is a manual configuration here: https://gist.github.com/dhoelzgen/cd7126b8652229d32eb4

How to create post request using angular.js and drywall (user management system) which needs csrf token?

How to create post request using angular.js and drywall (user management system) which needs csrf token ?
Some more information or a little bit of code of your side would be helpful. But I'll try:
A basic POST request would look sth like this:
function login() {
return $http.post('your-domain.com', {someData: "foobar"}).success(function(response) {
// do something with your data
}).error(function(error) {
// do something with the error
});
}
If you want to include the CSRF token for every request, you can read it out of your HTML code, and use the $http.defaults.headers object. Inside your app.js do this:
var yourApp = angular.module("yourApp", [
]).config(function() {
}).run(function($http) {
var csfrToken = $("meta[name='csrf-token']").attr("content");
$http.defaults.headers.post['X-CSRF-TOKEN'] = csfrToken;
});
Depending on your framework that generates the CSRF token, you have to adjust the jQuery selector $("meta[name='csrf-token']").attr("content").

AngularJS: Setting correct 'Referer' header for $http

It looks like when you send off a request using the $http service, the referer header is set to the base url without the angular $location information.
How do you go about appending the $location.path() to that header for all requests?
Our API calls will log that referer header when an error occurs; however, it would be very helpful if we could store the user's actual location ("stackoverflow.com/#/question/1234" opposed to just "stackoverflow.com/")
I ended up just doing something like this:
$httpProvider.interceptors.push(function ($location) {
return {
request: function (config) {
config.headers["RefererFullUrl"] = $location.absUrl();
return config;
}
};
});
It doesn't look like the browsers are too happy if you try to change the 'referer' url, so I'm just naming it something else, and looking for that header specifically on the server

angularjs not caching resource data . ( even after using cacheFactory )

I am trying to cache the response with angularjs but its not happening .
code #1
var app = angular.module("jsonService", ["ngResource"]);
app.factory("JsonFactory", function($resource,$cacheFactory) {
var cache = $cacheFactory('JsonFactory');
var url = "myurl?domain=:tabUrl";
var data = cache.get(url);
if (data==undefined) {
var retObj = $resource(url, {}, {
list: {
method: "GET",
cache: true
}
});
data = retObj;
cache.put(url, data);
};
return cache.get(url);
});
code #2
var app = angular.module("jsonService", ["ngResource"]);
app.factory("JsonFactory", function($resource) {
var url = "myurl?domain=:tabUrl";
console.log(url);
var retObj = $resource(url, {}, {
list: {
method: "GET",
cache: true
}
});
return retObj;
});
after both the code i wrote . when looking in to dev tools there always goes a XHR request in Network tab.
obviously : date does not changes . ( that's the whole point of caching )
After reading some of your responses, I think that what you are asking, is why does the network tab show a 200 response from your server, while using angular caching.
There are two caches. The first cache is angular's cache. If you see an xhr request in the network tab at all, then that means angular has decided that the url does not exist in its cache, and has asked the browser for a copy of the resource. Furthermore, the browser has looked in it's own cache, and decided that the file in its cache does not exist, or is too old.
Angular's cache is not an offline cache. Every time you refresh the browser page, angular's caching mechanism is reset to empty.
Once you see a request in the network tab, angular has no say in the server response at all. If you're looking for a 304 response from the server, and the server is not providing one, then the problem exists within the server and browser communication, not the client javascript framework.
A 304 response means that the browser has found an old file in its cache and would like the server to validate it. The browser has provided a date, or an etag, and the server has validated the information provided as still valid.
A 200 response means that either the client did not provide any information for the server to validate, or that the information provided has failed validation.
Also, if you use the refresh button in the browser, the browser will send information to the server that is guaranteed to fail (max-age=0), so you will always get a 200 response on a page refresh.
According to the documentation for the version of angular that you are using, ngResource does not support caching yet.
http://code.angularjs.org/1.0.8/docs/api/ngResource.$resource
If you are unable to upgrade your angular version, you may have luck configuring the http service manually before you use $resource.
I'm not exactly sure of syntax, but something like this:
yourModule.run(function($http)
{
$http.cache=true;
});
$cacheFactory can help you cache the response. Try to implement the "JsonFactory" this way:
app.factory("JsonFactory",function($resource,$cacheFactory){
$cacheFactory("JsonFactory");
var url="myurl?domain=:tabUrl";
return{
getResponse:function(tabUrl){
var retObj=$resource(url,{},{list:{method:"GET",cache:true}});
var response=cache.get(tabUrl);
//if response is not cached
if(!response){
//send GET request to fetch response
response=retObj.list({tabUrl:tabUrl});
//add response to cache
cache.put(tabUrl,response);
}
return cache.get(tabUrl);
}
};
});
And use this service in controller:
app.controller("myCtrl",function($scope,$location,JsonFactory){
$scope.clickCount=0;
$scope.jsonpTest = function(){
$scope.result = JsonFactory.getResponse("myTab");
$scope.clickCount++;
}
});
HTML:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular-resource.js"></script>
<script src="js/ngResource.js"></script>
<body ng-app="app">
<div ng-controller="myCtrl">
<div>Clicked: {{clickCount}}</div>
<div>Response: {{result}}</div>
<input type="button" ng-click="jsonpTest()" value="JSONP"/>
</div>
</body>
Screenshot:
[EDIT] for html5 localStorage solution
JSBin Demo
.factory("JsonFactory",function($resource){
var url="ur/URL/:tabUrl";
var liveTime=60*1000; //1 min
var response = "";
return{
getResponse:function(tabUrl){
var retObj=$resource(url,{},{list:{method:"GET",cache:true}});
if(('localStorage' in window) && window.localStorage !== null){
//no cached data
if(!localStorage[tabUrl] || new Date().getTime()>localStorage[tabUrl+"_expires"]) {
console.log("no cache");
//send GET request to fetch response
response=retObj.list({tabUrl:tabUrl});
//add response to cache
localStorage[tabUrl] = response;
localStorage[tabUrl+"_expires"] = new Date().getTime()+liveTime;
}
//console.log(localStorage.tabUrl.expires+"..."+new Date().getTime());
return localStorage[tabUrl];
}
//client doesn't support local cache, send request to fetch response
response=retObj.list({tabUrl:tabUrl});
return response;
}
};
});
Hope this is helpful for you.

Resources