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: *
Related
Whenever I make the API request with GET method, it is returning a 503 error from Google AppScript. However, this same request is successfully getting response consistently when run from Postman or the web-browser.
The AppScript code returns a JSON response out of the blue at first call and all consecutive calls return with the error 503. This server response is showing up specifically to the AppScript code here.
The detailed error message is as follows:
Exception: Request failed for https://api.dailymotion.com returned code 503. Truncated server response: Gone. (use muteHttpExceptions option to examine full response) (line 24, file "DailyMotion")
function dailymotionArtist() {
var artistchannelID = 'x24dh63';
var requestOptions = {
'headers': {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Cache-Control': 'no-cache'
},
'muteHttpExceptions': true,
method: 'GET'
}
var finalResponse2 = UrlFetchApp.fetch('https://api.dailymotion.com/user/' + artistchannelID + '?fields=followers_total%2Cviews_total', requestOptions);
Logger.log(finalResponse2.getContentText());
}
A 503 error message is generally representative of a server being unable to respond to a request temporarily, and is not normally a representation of an incorrect request - see description of the 503 code.
I would always suggest trying a request using Postman or another HTTP Client to test the API isn't just down temporarily before debugging a 503 code.
When I use the fetch API (Or xmlhttprequest) I get a 0 byte response. Here is a sample of my code:
fetch("https://myurl", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({content: content})
}).then(function(res){ return res.text()}).then(function(res){ return cb(res);});
In the network tab, and in the console.log(res) in the callback, the response is empty. I should note that the response is including a CORS response specifying my chrome extension (which is making the request)
Access-Control-Allow-Origin: chrome-extension://asdjkljuewyrjkhighqwend
When I use the requests library (python) and make the same request (copying and pasting the body of the request) I get a valid json response.
resp = requests.post("https://myurl", json=data)
resp.json() ->> {content}
Additionally, when I inspect the server after the Fetch requests, I can see that it happily responded with the json to the request, but something on the browser seems to be blocking it from getting through.
You need to move all XHR requests to the background part of your extension.
Chrome no longer accepts content scripts requests.
You can use runtime.sendMessage to send messages to a background process.
chrome.runtime.sendMessage(myMessageObject, async response => {
// Here is the response returned by the background process
});
And here is how to receive messages from the background perspective.
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
return true
})
I believe you're indeed looking at a CORS issue. Try including the following headers in the response from your server:
Access-Control-Allow-Origin: * // you already hve this one
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, PUT, POST, OPTIONS
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);
});
I have a problem with Angular 2 http.delete method. My code is below:
const headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});
this.http.delete(ConstVarService.url + 'api/tasks/UsunZapis', new RequestOptions({
headers: headers,
body: {tasksId: entryId}
})).subscribe((data) => {
console.log(data)
});
And when I execute, I gets the following errors:
OPTIONS http://192.168.13.36/pplus-dev/appapi/api/tasks/UsunZapis 405 (Method Not Allowed)
Failed to load http://192.168.13.36/pplus-dev/appapi/api/tasks/UsunZapis: Response for preflight has invalid HTTP status code 405
But in Postman everything works, the same URL, Content-Type etc.
In order to make a request that is cross-domain the browser does what is called a pre-flight check. You need to return the appropriate CORS headers in order to allow the browser to make requests.
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.