I wrote this in AngularJS service block and I can't get it to work properly:
app.factory('sfAttachment', ['$http', '$q', '$window', function($http, $q, $window){
var attachment = {};
//Save to server function for attachments
attachment.save = function( base64value, mimeType, currentDocTypeId, currentFilename, attachmentId ){
var data = {
"Body" : base64value,
"ContentType": mimeType,
"ParentId": currentDocTypeId,
"Name": currentFilename
};
var url = $window.__url;
var method;
var isUpdate = ($.trim(attachmentId) !== '');
if (isUpdate) {
url = url + attachmentId;
method = 'PATCH';
} else {
// Method for creation
method = 'POST';
};
var request = {
url: url,
method: method,
data: data
};
var deferred = $q.defer();
$http(request).then(function(response){
deferred.resolve(response);
console.log('file SAVED');
console.log(response);
}, function(event){
deferred.reject('The attachment could not be saved:' + event);
});
return deferred.promise;
}
return attachment;}]);
app.run(['$http','$window',function ($http, $window) {
var sessionId = $window.__sfdcSessionId;
$http.defaults.useXDomain = true;
delete $http.defaults.headers.common["X-Requested-With"];
$http.defaults.headers.common["Access-Control-Allow-Origin"] = "*";
$http.defaults.headers.common["Accept"] = "application/json";
$http.defaults.headers.common["content-type"] = "application/json";
$http.defaults.headers.common['Authorization'] = "OAuth " + sessionId ;
$http.defaults.headers.common['X-User-Agent'] = "MyClient" ;
}]) ;
I keep getting these errors:
Failed to load resource: the server responded with a status of 400 (Bad Request)
As well as this:
MLHttpRequest cannot load https://youri.cs22.my.salesforce.com/services/data/v26.0/sobjects/Attachment/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://youri--c.cs22.visual.force.com' is therefore not allowed access. The response had HTTP status code 400.
I added https://youri--c.cs22.visual.force.comto the remote Site settings in Salesforce but that still seem to be causing issues...
Any suggestions?
EDIT: I figured out the first part of my issue I needed to white list https://youri--c.cs22.visual.force.comin Remote Settings> CORS and not remote sites but I still get the Bad request error...
See the Edit:
EDIT: I figured out the first part of my issue I needed to white list https://youri--c.cs22.visual.force.comin Remote Settings> CORS and not remote sites but I still get the Bad request error...
Related
Im having trouble making REST API calls in my ionic app to my server. It shows the following error.
ionic.bundle.js:25005 OPTIONS https://website.com/api/ionic_test 406 (Not Acceptable)
XMLHttpRequest cannot load https://website.com/api/ionic_test. Response for preflight has invalid HTTP status code 406
API call code.
$http.post(API_ENDPOINT.url + '/ionic_test', user).then(function(result) {
if (result.data.status) {
storeUserCredentials(result.data.token);
resolve(result.data.msg);
} else {
reject(result.data.msg);
}
});
ionic.config.json
{
"name": "adminPanel",
"app_id": "",
"proxies": [
{
"path": "/api",
"proxyUrl": "http://website.com/api"
}
]
}
The problem is with your server. In the comments you said the API works in browser, but not in your app. That's because your browser doesn't send an OPTIONS "preflight" request, which Ionic does.
You need to either disable the preflight request, or configure your server to handle it properly.
Use these in your app config to resolve the preflight issue
$httpProvider.defaults.headers.common = {};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
Eg.
angular.module('yourApp', [])
.config(function ($stateProvider, $httpProvider, $urlRouterProvider) {
//To solve Response for preflight has invalid HTTP
$httpProvider.defaults.headers.common = {};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
//--------------------------------------
// your routes here
});
When I try to access WebApi from MVC, I get this error
XMLHttpRequest cannot load http://localhost:57997/Home/Get. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:64035' is therefore not allowed acces
Service.Js
app.service('MyService', function ($http) {
var ApiAddress = "http://localhost:57997/";
this.GetWebData = function () {
var Getdatas= $http({
url: ApiAddress + 'Home/Get',
type: 'GET',
dataType: 'json',
params: JSON.stringify(),
content:{'content-type' :'application/Json'}
})
return Getdatas;
}
});
Controller.Js
app.controller('WebCtrls', function ($scope,MyService) {
$scope.Hello = "Hello angular How r u...";
$scope.GetDb = function () {
alert('Hello..');
var SerData = MyService.GetWebData();
SerData.then(function (d) {
$scope.Emp = d.data;
})
}
})
WebApi
public JsonResult Get()
{
var x = prod.GetEmployees();
return new JsonResult { Data = x, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
Global.asax
in WebApi global file I wrote bellow code for cross page origin
protected void Application_BeginRequest()
{
string[] allowedOrigin = new string[] { "http://localhost:57997/" };
var origin = HttpContext.Current.Request.Headers["Origin"];
if (origin != null && allowedOrigin.Contains(origin))
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", origin);
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST");
//Need to add more later , will see when required
}
}
You can handle it by disabling web security option of chrome browser by following command from the folder location where chrome.exe is present. First close all instances of chrome. Then run following command
chrome.exe --disable-web-security
You can handle it at server side while filtering all request coming to server, add the header to response like this.
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
Below is my service call where I am trying to do a basic auth. I have checked multiple blogs could not find the solution for this.
Can anybody help me to solve this issue as I am getting below error:
XMLHttpRequest cannot load
Response for preflight has invalid HTTP status code 401
I could not find the basic auth in the network tab in developer options also.
function() {
"use strict";
var APIservice = function($http, $base64) {
var getDetails = function(postData) {
$http.defaults.headers.common['Access-Control-Allow-Origin'] = "*";
$http.defaults.headers.common['Access-Control-Allow-Methods'] = "GET,PUT,POST,DELETE,OPTIONS";
$http.defaults.headers.common['Access-Control-Allow-Headers'] = "Content-Type, Authorization, Content-Length, X-Requested-With";
$http.defaults.headers.common['Content-Type'] = undefined;
console.log($http.defaults.headers.common.Authorization);
//console.log($http.defaults.headers.common.Authorization);
return $http.get('http://52.74.68.202:8080/rest/v1/step/all')
.then(function(response, headers, config) {
console.log(response);
return response;
});
};
return {
getDetails: getDetails
}
}
var module = angular.module('expframework');
module.factory("APIservice", APIservice);
module.run(['$http', '$base64', function($http, $base64) {
var authdata = $base64.encode('test:test');
$http.defaults.headers.common['Authorization'] = 'Basic ' + authdata;
}]);
module.config(['$httpProvider', '$base64', function($httpProvider, $base64) {
var authdata = $base64.encode('test:test');
$httpProvider.defaults.headers.common['Authorization'] = 'Basic ' + authdata;
}])
}();
It is working in Safari and emulators but not working in Chrome and Firefox
Please help me to fix this. Thanks in advance.
Since your server threw a 401, I guess it tried to authenticate the preflight request. From https://stackoverflow.com/a/15734032/1225328:
The W3 spec for CORS preflight requests clearly states that user credentials should be excluded.
[...]
Simply have the server (API in this example) respond to OPTIONS requests without requiring authentication.
Im trying to send an request in my angularjs application to google API to get the attractions in a radius around an location. But I get this error message in chrome:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.
I've tried both json and jsonp but the result is the same. :S
$http.get('https://maps.googleapis.com/maps/api/place/radarsearch/json?location=51.503186,-0.126446&radius=5000&type=museum&key=<MYKEY>')
.then(function(response) {
$scope.dataResult = response.data;
});
$scope.getlocation = function() {
$scope.method = 'GET';
$http({ method: $scope.method, url: "https://maps.googleapis.com/maps/api/place/radarsearch/json?location=51.503186,-0.126446&radius=5000&type=museum&key=<MYKEY>&callback=JSON_CALLBACK" }).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
console.log(data);
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
I dont want to show result on a map, I only want it in list format.
This is CORS issue, from the client-side you can enable cors requests like this.
angular.module('yourapp').config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
The problem with your case is , https://maps.googleapis.com/maps/api/place/radarsearch/json?location=51.503186,-0.126446&radius=5000&type=museum&key=<MYKEY> does not allow your origin to have access to the response. Therefore you are not able read it.
I hope you have a valid key and also while registering you have listed your localhost in the place of domain... as google needs to know these.
I am using express and angular for my app.
Suppose I have the following factory:
angular.module('LiveAPP.factory',[])
.factory('dataFactory', ['$http', dataFactory])
function dataFactory($http){
var dataFactory = {};
dataFactory.checkDb = function(){
return $http({
method: 'GET',
url: '/artistsearch',
data: "Need this data to go to the request body"
})
}
return dataFacory;
}
And on the server side I have:
app.js
app.get('/artistsearch',dbhelpers.checkDbArtist)
dbhelpers.js
exports.checkDbArtist = function(req,res,next){
var newArtist = req.body;
}
For some reason when checkDb is invoked my get request is not passing on data into my req.body in checkDbArtist. My request body evaluates to {}. Anyone have any idea why?