Angular http GET 405 (Method Not Allowed) - javascript

I'm implementing another function in an application (made with angular), I call an API (made with Lumen) and it returns a 405 error whem i tried in local and "XMLHttpRequest cannot load Response for preflight is invalid (redirect)" when i tried on the server. I read about CORS but it's already implemented, I think if it isn't none of others functions would work.
Another thing, if I make the call with Advanced Rest Client it works fine :(
sorry about my english, i don't speak it so much.
function on application
$scope.agencias = [];
$http({
method: 'GET',
//url: 'http://api-beta.grupoaldorf.com.mx/agencias/',
url: 'http://localhost:8000/agencias/',
headers: agenciaMazda.headers
}).then(function successCallback(response) {
$scope.agencias = response.data;
console.log("regreso del http");
console.log($scope.agencias);
}, function errorCallback(response) {
//callback(false);
});
route on web.php
$app->get('agencias','CitasController#agenciasDisponibles');
controller in CitasController.php
public function agenciasDisponibles(Agencia $agencia){
$fabricante = $this->request->header('Aldorf-App');
$disponibles = Agencia::where('fabricante', $fabricante)->where('mostrar', 1)->select(['codigo', 'nombre'])->get();
return $disponibles;
}

Finally i solved it, it was really dumb, i added a slash at the end of the uri xD it had to be "http://localhost:8000/agencias" instead of "http://localhost:8000/agencias/"

Related

AngularJS $http POST turn into GET

I have a route
Route::post('/updateLogo', 'CaptivePortalController#updateLogo');
Then I make a POST here
$http({
method: 'POST', <----- I did a POST
url: '/updateLogo',
headers: { 'Content-Type': undefined },
transformRequest: function (data) {
console.log("data coming into the transform is ", data);
var formData = new FormData();
formData.append("company_logo_path", data.files);
console.log($scope.files.company_logo_path);
return formData;
},
data: { files: $scope.files.company_logo_path }
})
.then(function successCallback(response) {
console.log("success");
console.log(response);
$('.save-fade').delay(500).fadeOut(1000);
}, function errorCallback(response) {
console.log("fail");
console.log(response);
});
When I browse the file, and submit the form, I kept getting
405 in my Network tab on Chrome Dev Tool.
Then, I click on it, I see
MethodNotAllowedHttpException in RouteCollection.php line 218:
I know that I'm NOT suppose to make a GET to a POST route, but Why does it make a GET request instead of a POST?
Request URL:http://l.ssc.com:8888/en/updateLogo
Request Method:GET <------
Status Code:405 Method Not Allowed
Remote Address:127.0.0.1:8888
Referrer Policy:no-referrer-when-downgrade
What did do wrong here ?
Any hints ?
This looks like a re-direction taking place.
refer : $http.post() method is actally sending a GET
Please check your route configuration at the server, make sure it is exactly the same as you're requesting.
If you're requesting a '/myroute' but you've defined the route as '/myroute/' then your server could be redirecting to '/myroute'.
All re-directions are done using a GET.
And since the route doesn't allow GET request, it's returning a 405.

Cross domain HTML parsing using AngularJS [duplicate]

This question already has an answer here:
Why does my JSONP request give me Uncaught SyntaxError: Unexpected token < (less than)?
(1 answer)
Closed 5 years ago.
We are working on java project in which backend is java + spring and fronted is angular 2 + HTML.
I want to do cross domain html parsing but we don't have permission to access external links on server side as we have some security issues for outsite domains, so we have to get the DOM content of link on client side using jquery.
I have tried these:
var url = "http://xyz.aspx";
$http({
method: 'JSONP',
url: url,
params: {
format: 'jsonp',
json_callback: 'JSON_CALLBACK'
}
}).
success(function(response) {
$scope.test = response;
}).
error(function(status) {
//your code when fails
});
The external link which I need to parse contains many href links. I also need to parse content of those links.
Have tried above mentioned code:
getting error in console - Uncaught SyntaxError: Unexpected token < on
xyz.aspx page
What will be best solution to get content of the pages and pass to server side for parsing?
Solution 1)
getting error in console - Uncaught SyntaxError: Unexpected token < on xyz.aspx page
This means that the server callback isn't a valid JavaScript application. Please ensure your server returns a valid JavaScript application. In that way this error will go away. JSONP needs a valid JavaScript application response to make it work. For example this is how a JSONP callback should look like:
jsonCallback(
{
sites: [
{
siteName: "Test"
}
]
}
);
Solution 2)
If your server side does not return a JSON Object try to use a GET request and enable CORS.
$http({
method: 'GET',
url: "http://xyz.aspx",
}).success(function(response) {
$scope.test = response.data;
}).error(function(status) {
//your code when fails
});
Solution 3)
If you are still be unable to add CORS to your backend you could create an PROXY application yourself. This for example is an public CORS Proxy https://crossorigin.me/. Adding an example on how to create a proxy service would be to much. Please research by yourself. There are a lot of examples in the web.
See ng.$http. Your URL is missing the callback parameter,instead of giving like
json_callback: 'JSON_CALLBACK'
Try below way
$http({
method: 'jsonp',
url: 'http://xyz.aspx?callback=JSON_CALLBACK',
params: { name: 'xyz' }
}).success(function(data, status , header, config) {
console.log('success');
}).error(function(data, status , header, config) {
console.log('error');
});

How to "get" from NodeJS with AngularJS

I started an AngularJs App and to retrieve some data from database I'm using NodeJS (totally new to me), on the console of NodeJS it works and also typing the URL directly in the browser but when I try to get the information needed using http.get() in AngularJS using the same URL in the browser I get 404 not found.
I figured it would be a cors problem so I added
require('cors') in the nodeJS app and still doesn't work
Can anyone help me with that ?
Am I right making separate apps for Angularjs in front-end and NodeJS in the Backend or should I assemble them in only one application ?
Thank you for your help
This is the AngularJS code:
$scope.keyLoad = function () {
$http.get("localhost:8080/product")
.success(function (response) {
$scope.keys = response;
console.log(response)
})
};
$scope.keyLoad();
I get 404 not found. I figured it would be a cors problem
If it says it is a 404 error then it is a 404 error and not a CORS problem.
Look at your code:
$http.get("localhost:8080/product")
That URL is missing the scheme. It is a relative URL.
You are going to be requesting something like http://example.com/myapp/localhost:8080/product.
Put http:// or https:// in front of it.
You should use $http service.
For example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Or
$http.get('/someUrl', config).then(successCallback, errorCallback);

AngularJS $http.post() firing get request instead of post

i building an API service in angular and laravel, when i firing a GET call to the API everythings work fine, but when i fire POST call the service still use GET method instead of POST.
that is my service:
function LeadsAPI($http,$q,BASE_URL)
{
this.updateLead = function (lead_data) {
var url = BASE_URL+"/leads/update/";
var deferred = $q.defer();
$http.post(url , lead_data).then(function(response){
deferred.resolve(response.data);
});
return deferred.promise;
}
}
i call to this function from a Controller:
LeadsController.$inject = ['$scope', 'LeadsAPI'];
function LeadsController($scope , LeadsAPI)
{
LeadsAPI.updateLead({'lead_id' : res._id, 'the_lead': {'fist_name' : 'asd asd'}}).then(function (res) {
console.log(res);
});
}
i tried pass the parameters as a string ("a=b&c=d...") and added header :
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
in the run function at my App module instantiation but yet, i keep getting 405 (Method Not Allowed) error.
any ideas why and how to solve it? thank you very much all! :)
Seems the question is old and unanswered but google led me here. I hope someone will find this answer useful.
I had the same problem. $http was set to POST but server was returning error from GET request.
After checking the headers in a web inspector it shows the browser actually did two requests:
update/ 301 text/html angular.js:11442
update 405 xhr https://test.site/post/update
The first one is the one from $http and the second one is after a redirect.
As you can see the trailing slash URL is redirected to a non trailing one. With this redirect a POST request gets also changed to GET as well.
The solution is to change your request url to not contain trailing slashes:
url: BASE_URL+"/leads/update",
The GET works fine ... good
The POST returns 405 - Method not allowed
It sounds like it is doing a POST and the server you are posting to does not support POST requests to the endpoint in question
Can you please provide more information, such as the HTTP request and response headers when you make a GET request and the same for the POST request
You can access the header information via the NET tab in Firefox's Firebug or in Chrome console
Be sure that your API method is ready to handle a POST request. Maybe Angular is actually firing a POST request, but your method is expecting a GET.
If you are sure Angular is really firing a GET request instead of a POST for some reason, try to explicitly set the HTTP method on the $http object:
$http({
method: 'POST',
url: BASE_URL+"/leads/update/",
data: lead_data
}).then(function (response) {
deferred.resolve(response.data);
});

CasperJS AJAX form via POST not working

I am trying to get CasperJS to post a form using AJAX - it doesn't seem to work for me, the code is below:
this.then(function() {
response = this.evaluate(function() {
params = $("#offer").serialize();
//require('utils').dump(params);
$.ajax({
type: "POST",
url: 'http://www.example.com/getoffer.php',
data: params,
success: function (data) {
//return data.responseText;
return __utils__.sendAJAX(url, 'POST', params);
},
error: function (xhr,status,error){
return error;
}
});
});
this.echo(response);
});
CORS?
(I'm so tempted to just leave that as my shortest ever StackOverflow answer :-)
Your JavaScript is being executed from inside the browser, and the security model will apply. Your "origin" will be the page that CasperJS is requesting; if that is not "www.mysite.com" (or if it is but is HTTPS), then the browser will refuse to send it.
This answer https://stackoverflow.com/a/16221536/841830 says --web-security=false (give that as a casperjs commandline option) will get around CORS restrictions.
This issue seems to be doing the same as you, so if it is not a CORS problem, it might give you some other ideas: http://code.google.com/p/phantomjs/issues/detail?id=28

Categories

Resources