AngularJS $http POST turn into GET - javascript

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.

Related

Javascript REST API with body in GET

I'm working in Javascript (frontend) and have a colleague working in the backend with NodeJS.
When calling a GET request, he asks me to put the data in the body, but I could not figure out how to do that. (If I use this code to a POST request, it works fine).
Could you tell me if this is possible and how to do it? He says that it is possible, but I've googled a lot and could not find the correct way to do that.
ERROR that I get: "Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body."
let URL = "http://localhost:3000/verifyUser";
let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2NjJDMTRBNk";
fetch(URL, {
method: request,
mode: 'cors',
body: JSON.stringify({
user: 'Carlos6',
password: '543534543',
email: "algo6#gmail.com"
}),
headers: {
'Accept' : 'application/json',
'Content-type': 'application/json; charset=UTF-8',
'auth-token': token
}
}).then(function (response) {
if (response.ok) {
return response.json();
}
return Promise.reject(response);
}).then(function (data) {
console.log(data);
}).catch(function (error) {
console.warn('Something went wrong.', error);
});
You are using HTTP GET and sending a body.
If you want to send a body (JSON) you should use the PUT and POST.
The best will probably be to:
change your client code to method: "PUT"
change the server to access PUT request
If you want to know which one to chose look at this question:
( PUT vs. POST in REST)
If you wish to send a request with a body then you should make a POST-request and not a GET one. GET-request cannot have a body by its nature and primary goal.
All params of GET-request must be indicated in the URL itself only.

google invisible reCaptcha server side validation is failing

i have integrated the invisible reCaptcha in my application and the client side response is coming as part of solving the image challenge. i am then calling a angular function to validate user response on server side using below code. where onloginSubmit(token) is the success call back.
<button id="btnLogin" ng-disabled="loginForm.$invalid"
class="g-recaptcha primarybtn margin-left-zero form-control-input"
data-sitekey="{{public_key}}"
data-callback='onloginSubmit'>{{'label_login' |
translate}}</button>
<script>
function onloginSubmit(token) {
angular.element(document.getElementById('loginForm')).scope().verifyReCaptcha(token);
};
</script>
in angular i am calling the verifyReCaptcha as below.
$scope.public_key = "------ My Site Key -------";
$scope.private_key = "------ My Secret Key -------";
$scope.verifyReCaptchaURL = "https://www.google.com/recaptcha/api/siteverify";
$scope.verifyReCaptcha = function(reCaptchaToken){
var captchaData = {
secret : $scope.private_key,
response : reCaptchaToken
}
$http({
headers: {
'Accept': 'application/json,text/plain',
'Content-Type': 'application/json;application/x-www-form-urlencoded;charset=utf-8;',
},
url: $scope.verifyReCaptchaURL,
method: 'POST',
data: captchaData
}).success(function (data) {
console.log("success");
$scope.login();
}).error(function (data) {
console.log("error");
$window.location.reload(true);
});
};
when i hit the api service https://www.google.com/recaptcha/api/siteverify . i get the below error.
Failed to load https://www.google.com/recaptcha/api/siteverify: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 405.
i couldnt find more documentation for the issue.
what is it that i am doing wrong and also if there is any error the recaptcha does not come up and the login button which i am using fails to respond.
n the request i am mentioning the Method as Post, the method is over ridden as Options and the request payload which i am sending is not present. this is what i got in the networks tab
Request URL:https://www.google.com/recaptcha/api/siteverify
Request Method:OPTIONS
Status Code:405
Remote Address:10.120.118.50:8080
Referrer Policy:no-referrer-when-downgrade
Most of the thing you did a great job. One thing is to require in your application is communicate to an external domain so you can include HTTP header content type is include a JSONP format.
$http({
headers: {
'Accept': 'application/json,text/plain',
'Content-Type': 'application/jsonp;application/x-www-form-urlencoded;charset=utf-8;',
},
url: $scope.verifyReCaptchaURL,
method: 'POST',
data: captchaData
}).success(function (data) {
console.log("success");
$scope.login();
}).error(function (data) {
console.log("error");
$window.location.reload(true);
});

Error with CORS - Angularjs $http.post

I am trying to do a $http.post, but this response give me this error.
XMLHttpRequest cannot load http://XXXXXXXXX:2222/server/api/v1/controllers. Response for preflight has invalid HTTP status code 403
All of I read on internet sais that Its a fault by the CORS, I try to solve this with no success.
Here is my $http.post method.
// Set the Content-Type
$http.defaults.headers.post["Content-Type"] = "application/json";
// Delete the Requested With Header
delete $http.defaults.headers.common['X-Requested-With'];
var config = {
method: 'POST',
headers: {'Content-Type': 'application/json; charset=utf-8'}
}
$http.post("http://XXXXXXXXX:2222/server/api/v1/controllers", objToSave , config)
.then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
console.log(response)
}, function errorCallback(error) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log(error)
});
I am using Angular v1.5.5.
I hope You can help me,
Regards!
chrome first send preflight request to check if server responds properly. If server properly handles that preflight request, then original request will be sent by chrome. Try to add below line in your server request handler header.
Access-Control-Allow-Origin: *

Node.js piping streams with ajax and nodes http module

I have an express app with some ajax, calling some remote endpoints. At the moment, my api calls are posting to an endpoint on my local server. Express listens on these endpoints and pipes the request to the remote server and resolves the response.
This is working for most of my endpoints, except for one POST method which requires a query parameter of code and a body of type Array[int]. The response for each request to this endpoint returns 405. If I call the server endpoint directly within the ajax request, It returns successful. Does this issue ring a bell for anyone?
Here is what the data flow looks like.
$.ajax({
type: "POST",
url: "/promos/validate?code=testing",
data: JSON.stringify([1]),
success: function(data) {
console.log(data)
}.bind(this),
error: function(xhr, status, err) {
console.log(status)
}.bind(this)
});
And then we route with express
router.post('/promos/validate', function(req, res) {
pipe(req, res).post(http://remoteUrl/promos/validate/code=testing);
});
In the post method, lives the http.request function which sends the following object as the options parameter
{
protocol: 'http:',
query: '?code=testing',
host: 'remote-api.com',
port: 80,
hostname: 'remote-api.com',
href: 'http://remote-api.com?code=testing',
path: '/promos/validate',
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Content-Length': 8 }
}
And finally we stream the request body to the server with write. Every time this happens, it returns 405. Any ideas?
Two things: the ajax request needed to set the content type to application/json and it turns out that the request was hitting 405 because the query was being separated into its own property when it should have been appended onto the 'path' property option.
I found this out by viewing the options list at Node.js docs - https://nodejs.org/api/http.html#http_http_request_options_callback

how to get json string from angular $http post request

I am sending this POST, I want to see the string that get's sent in the request before I send it.
Here's Plunker
$http.post('/someUrl', {msg:'hello word!'}).
then(function(response) {
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
I guess what I am trying to do is see the JSON string being sent to the server.
if you are hitting the url with config option like this
var config = {
headers: { 'Content-type': 'application/json' },
'dataType': 'json'
};
var data = {
name: 'intekhab',
age:26,
};
$http.post('/admin/header', data, config).then(function(response){
console.log(response);
});
Then you can see the data what are send. Open your browser console and click network then under network click your url what you have hit
And now see the look at Request Payload under header tab
There your data will be revealing what you have send to server.
And if you are not using config option like this
var data = {
name: 'intekhab',
age:26,
};
$http.post('/admin/header', data).then(function(response){
console.log(response);
});
Then do the same as above only difference is where you have seen the data under Request Payload, now you will see the same data under Form Data
From what I understand, I think you want different handlers if the request succeeds or fails. You can do it in this way:
$http.post('/someUrl', {msg:'hello word!'}).
success(function(response) {
// this callback will be called asynchronously
// when it succeeds
}).error(function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

Categories

Resources