I'm not very good with angular. I want to post to a web service, sending some xml with my search parameters. I don't want to send the parameters in the query string. I've read the official documentation, but I'm still confused. I'm mostly hung up on how to define the $resource to be able to post the way I want.
The error I get is: POST 'https://someWebservice/searchnet'::ERR_INSECURE_RESPONSE
My code is below:
'use strict';
angular.module('app').controller('inventorySearchController', inventorySearchController);
inventorySearchController.$inject = ['$scope','$http', '$resource'];
function inventorySearchController($scope, $http, $resource) {
console.log("controller initialized...");
$scope.callService = function(){
console.log("callService function called...");
var urlSearchService = 'https://someWebservice/search';
var skuVal = $scope.skuField;
var mVenVal = $scope.mVendorField;
//need to somehow specifiy that xml is a #FormParam
var xmlItemSearchRequest = "<ItemSearchRequest>"
+"<skuid>" + skuVal + "</skuid>"
+"<mvendor>" + mVenVal + "</mvendor>"
+"</ItemSearchRequest>";
console.log('calling: ' + urlSearchService + 'sending xml: ' + xmlItemSearchRequest);
var Results = $resource(urlSearchService, {
save: {
method: 'POST',
isArray: true
}
});
var result = Results.save();
console.log('Results: ' + Results);
console.log('result: ' + result);
var successfunction = function(){
$scope.searchResults = data;
console.log('call to ' + urlSearchService + ", was a success.");
};
var errorfunction = function(){
console.error('Calling error', status, data);
};
};
};
The error shown is not about how you posted data. Instead, response was not signed by a valid SSL certificate (or the certificate could not be accepted). That is due to the use of HTTPS protocol. You should consider using HTTP instead.
You can try the approach suggested here to confirm that this is the case.
Related
I'm making http get call from angularJS function. Call works perfectly and get the response back but I need to store response in a variable so I can use it outside of $http. I tried to keep in $scope.data.submissionFileID but alert($scope.data.submissionFileID) says undefined. Also I want me make this call synchronous. I'm new to this, can you please help to modify this below code?
$scope.openWindow = function (e) {
var url = '/Submission/GetSubmissionFileInfo?' + 'id=' + SubmissionID;
$http.get(url).success(function (response) {
$scope.data.submissionFileID = response; // response is an integer such as 123
});
alert($scope.data.submissionFileID); // This is undefined, what should I do to fix it?
var content = "<h7><b>" + "Created at </b>" + $scope.data.submissionFileID + "</h7><br><br>";
}
Something to consider is that the alert(...) is being called before the async function has a chance to complete. An option would be to send the response off to another function that sets the $scope variable and does whatever else you might want.
$scope.openWindow = function (e) {
var url = '/Submission/GetSubmissionFileInfo?' + 'id=' + SubmissionID;
$http.get(url).success(function (response) {
$scope.doTheThing(response);
});
}
$scope.data = {}
$scope.doTheThing = function(response) {
$scope.data.submissionFileID = response;
}
in the HTML template file...
<div ng-if="!data.submissionFileID">Retrieving Data....</div>
<div ng-if="data.submissionFileID">
<h7><b>Created at </b> {{data.submissionFileID}}</h7>
</div>
First to say, when I enter the put command in POSTMAN (its then a POST there) I have no problems. Trying to execute the PUT command in code I receive a http 405 error.
The exact error is:
<p>Problem accessing /api/portfolio/createTransaction. Reason:
<pre> Method Not Allowed</pre></p><hr>
This is my code:
const app = angular.module('demoAppModule', ['ui.bootstrap']);
const apiBaseURL = "/api/portfolio/";
console.log(apiBaseURL);
app.controller('DemoAppController', function($scope, $http) {
const demoApp = this;
demoApp.createTransaction = function () {
console.log("Initiating createTransaction...")
var transactionDetails = $.param({
Reference: $scope.reference,
Quantity: $scope.quantity,
TradeDate: $scope.tradeDate,
});
const createTransactionURL =
apiBaseURL
+ "createTransaction";
console.log("Executing flow");
console.log("Transaction URL = " + createTransactionURL);
console.log("Transaction Details = " + transactionDetails);
$http.put(createTransactionURL, angular.toJson(transactionDetails))
.then(function (transactionDetails, status, headers){
$scope.ServerResponse = transactionDetails;
})
.catch(function (transactionDetails, status, header, config) {
$scope.ServerResponse = htmlDecode("transactionDetails: " + transactionDetails +
"\n\n\n\nstatus: " + status +
"\n\n\n\nheaders: " + header +
"\n\n\n\nconfig: " + config);
});
};
});
Appreciate any help!
The server is rejecting your request, likely because it doesn't allow PUT requests.
It's probably expecting a HTTP POST instead of a PUT.
If so, change $http.put to $http.post - the method signatures are identical.
If you think the server should be accepting a PUT, you'll need to check why the server side code is rejecting it, which won't be apparent in the client code
This is my first question, excuse my english.
I'm working with angular and I'm using http.post for all (get and post info). And how this is wrong, I'd start to use http.get for request the record from Database.
I'm using this:
$http.get("empresa.php",{params:{id:-1,action:"get"}})
I expect receive something like this:
empresa.php?id=-1&action=get
But not work, because send this:
empresa.php?query=%7B%22id%22:-1,%22action%22:%22get%22%7D
Could you help me?
query is not so I'expect to be.
I'm using Angularjs 1.5.8
EDITION
Te factory is this:
app.factory("Data", ['$http',
function($http, ) { // This service connects to our REST API
var serviceBase = 'service/';
var obj = {};
obj.get = function(q,p) {
console.log(p);
return $http.get(serviceBase + q + ".php",{params:p}).then(function (results) {
return results.data;
});
};
obj.post = function(q, object) {
return $http.post(serviceBase + q + ".php", object).then(function(results) {
return results.data;
});
};
obj.put = function(q, object) {
return $http.put(serviceBase + q + ".php", object).then(function(results) {
return results.data;
});
};
obj.delete = function(q) {
return $http.delete(serviceBase + q + ".php").then(function(results) {
return results.data;
});
};
return obj;
}
]);
for POST work fine, but for GET doesn't work :(
New Edit
Here you can see how is that I have the code, how use and the response
Edit - Finalized
At the end, I resolved using $httpParamSerializer to serialize the json object and put it directly on call to empresa.php
Thanks to all for the help!!!
Use $httpParamSerializer to build the url query for you.
var params = {id:-1,action:"get"};
var query = $httpParamSerializer(params);
$http.get("empresa.php?" + query);
Try not using the $http.get shortcut method.
$http({
url: "empresa.php",
method: "GET",
params: {id:-1, action:"get"}
});
Or else you can create the url yourself.
$http.get('empresa.php?id=' + -1 + '&action=' + 'get');
I'm struggling in my first test so please bear with me.
I want to test a function that make a http post:
$scope.formData= 'client=' + $scope.client_selected + '&version=' + $scope.version_selected + '&modules=' + $scope.client.modules;
var response = $http.post('http://localhost:8080/mavenproject8/lol/form', $scope.formData);
response.success(function (data, status, headers, config) {
$scope.validity = true;
$scope.status = "true";
});
response.error(function (data, status, headers, config) {
$scope.status = "false";
alert("Exception details: " + JSON.stringify({data: data}));
and my test looks like this:
...
beforeEach(inject(function ($injector) {
// Set up the mock http service responses
$httpBackend = $injector.get('$httpBackend');
$httpBackend.when('POST', 'http://localhost:8080/mavenproject8/lol/form', data)
.respond([200, {success: true, errors: [{}]}]);
and this is the it block:
it('should succeed when everything is correct', function () {
$rootScope.client.modules=["360"];
$rootScope.version_selected="2.4.0"
$rootScope.client_selected="NSM";
$rootScope.formData='client=' + $rootScope.client_selected + '&version=' + $rootScope.version_selected + '&modules=' + $rootScope.client.modules;
$httpBackend.expectPOST('http://localhost:8080/mavenproject8/lol/form',$rootScope.formData);
$rootScope.myFunc();
expect($rootScope.validity).toBe(true);
});
But this test doesn't pass, with the error:
Error: No response defined !
I feel like I'm so close but I can't make it work. I would be grateful if you could help me. Thank you!
Actually, your expected post request doesn't specify a response, that's why you see that error, so all what you have to do is:
$httpBackend.expectPOST('http://localhost:8080/mavenproject8/lol/form').respond(200,{});
//don't forget to make the flush after the function call.!!
$rootScope.myFunc();
$httpBackend.flush();
( you can dont need the $httpBackend.whenPost because that's useful when you want to create a back end definition, and specify the response( get case for example) so you can remove it, and your test will still pass.)
In my angular app the global $http headers are defined for every request, like this:
function useBasicAuth(username, hash) {
var encoded = btoa(username + ':' + hash);
$http.defaults.headers.common.Authorization = 'Basic ' + encoded;
}
How to disable sending this information, when for example the user logs out, and the authentication is no longer required?
What I found as a working solution was to redeclare the $http.defaults.headers.common Object so it won't contain the headers.
Example:
function useBasicAuth(username, hash) {
var encoded = btoa(username + ':' + hash);
$http.defaults.headers.common.Authorization = 'Basic ' + encoded;
}
This, however won't delete the cached credentials from the browser. To overcome this, I've made a simple - and not asynch call to generate a bad request on purpose.
This is the function for this in my accountServices factory:
function checkAuth(username, hash) {
var encoded = btoa(username + ':' + hash);
var result = false;
$.ajax({
type: "POST",
beforeSend: function (request) {
request.setRequestHeader("Authorization", 'Basic ' + encoded);
},
url: "user/current",
statusCode: {
401: function () {
result = false;
},
200: function (response) {
result = response;
}
},
async: false
});
return result;
}
To log the user out, I call this function:
function useBasicWithoutAuth() {
accountServices.checkAuth('logout','logout');
$http.defaults.headers.common = {Accept: "application/json, text/plain, */*"};
}
So what this does, is it first sends a request to a protected URL, with a fake and non-existant user, so it's basically the same, as if the prompt would appear to you, and you'd click cancel.
After this has been done, there's no cached data in the browser, we can simply remove the headers from Angular, so it won't send any Authorization information, where it's not needed.