Angular httpClient - not catching PHP error object [duplicate] - php

This question already has answers here:
PHP: How to send HTTP response code?
(8 answers)
Closed 1 year ago.
I am tasked with connecting to an old php login api which simply returns a success or error message response object.
When I connect with the correct credentials I receive the success object and when do not I receive the error. Great!
However, httpClient does not seem to be recognizing the error object. Therefore, the object is accepted as a successful response object regardless of whether it is or it isn't.
The two relevant lines of php code:
$response = array("error" => "Combinación user-pass errónea", "success" => false, "status" => 500, "message" => "Error");
echo $json_response = safe_json_encode($response);
I then added a couple more properties to the error response in the hope of it being recognized:
$response = array("error" => "Combinación user-pass errónea", "success" => false, "status" => 403, "message" => "Error");
No luck...
I have then converted the observable into a promise so as to make the process as close as possible to the code used on an AngularJS app which uses the same login api:
let httpOptions = {
headers: new HttpHeaders(
{ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }),
};
let params = new HttpParams({
fromObject: { action: "login", username: credentials.username, password: credentials.password },
});
this.httpClient.post(`http://xxxxxxxxxxx/user_controller.php`, params.toString(), httpOptions).toPromise()
.then( data => console.log(data),
err => console.log(err) );
Still no luck...

The $http.error handler is triggered by server errors like 500 or 401;
If you wish to trigger a 401 error (unauthorized) for a bad login, do this:
if ($loginFailed) {
header("HTTP/1.1 401 Unauthorized");
exit;
}
Your angular code will pick that up as an error.
If you want to go on sending errors back the way you are currently, pick them up in the success callback, since the call was actually successful according to the server.
this.httpClient.post(`http://xxxxxxxxxxx/user_controller.php`, params.toString(), httpOptions).toPromise()
.then( data => {
console.log(data);
if (JSON.parse(data).error) this.triggerErrorResponse(data.error);
}, err => console.log(err) );

Related

Getting 409 error when calling php from my React application

I am trying to call a simple php file from my React application which will send an email with the details from a contact form. For some reason when the React code executes the fetch of the PHP file, it returns a 409. However, if I manually post the URL into another tab it works as expected, and subsequent calls from my React application then work as expected!
This is my React code:
var url = '/backend/sendmail.php?subject=New Website Enquiry&to=info#site.co.uk&msg=' + msg
console.log(url)
console.log('sending')
fetch(url,
{
'headers': {
'Accept': 'text/html',
'Content-Type': 'text/html'
},
'method': 'GET',
})
.then(
(result) => {
console.log(result.status)
if (result.status === 200) {
console.log('success')
this.togglePop();
this.setState({
name: "",
email: "",
phone: "",
message: "",
terms: false,
})
} else {
console.log('failed')
this.setState({ openError: true })
}
},
(error) => {
console.log('ERROR')
console.log(error)
this.setState({ openError: true })
}
)
And this is my PHP file:
<?php
//header("Access-Control-Allow-Origin: *");
header('Content-Type: text/html');
// error handler function
function customError($errno, $errstr) {
error_log($errstr);
http_response_code(500);
}
// set error handler
set_error_handler("customError");
http_response_code(200);
// send email
mail($_GET["to"],$_GET["subject"],$_GET["msg"],"From: donot.reply#site.co.uk","-f donot.reply#site.co.uk");
error_log($_GET["subject"].":\n".$_GET["msg"], 0);
echo 'OK';
?>
I have spent several days trying to figure out why this is happening. My htaccess file seems OK as once I have made one succesful call to the PHP file it works after that!
It's not a CORS issue as the file is on the same domain.
Anyone got any ideas?
You are sending the wrong request to the server, and that's why you get a 409 error. You should encode the URL params before sending a request
const url = '/backend/sendmail.php?subject=New Website Enquiry&to=info#site.co.uk&msg=' + msg;
const encoded = encodeURI(url);
console.log(encoded)
// expected correct URI: "/backend/sendmail.php?subject=New%20Website%20Enquiry&to=info#site.co.uk&msg="
You can read more about it here

fetch returns undefined error in Web notification Push

I am currently studying web notification and I stumbled in this guide. Currently everything's good but I seems to have an error in fetch() as it returns an undefined response error.
function sendSubscriptionToBackEnd(subscription) {
return fetch('send_notification.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(subscription)
}).then(function(response) {
console.log(response);
if (!response.ok) {
throw new Error('Bad Status code from server');
}
return response.json();
}).then(function(responseData) {
if (!(responseData.data && responseData.data.success)) {
throw new Error('Bad response from server.');
}
});
}
send_notification.php
<?php
echo json_encode(array("response"=>"ok"));
?>
This is how it looks like when it's passed:
I don't know why I'm getting no response from my send_notification. This is my whole file: https://www.mediafire.com/file/nbxe6ks3sjntjj0/push_notification2.zip/file
---------EDIT-----------
and this is what I meant about the undefined response.
The response object has no ok property. ok is the string value of the response property, therefore your logic should be:
if (response.response != 'ok') {
// your logic...
}
You're going to have the same issue with response.json(), however there's no logical guess I can make for what you're expecting that to be given the output in the images you've shown.
I tried your code, and it is working without any problem. console.log(response) is returning 200 OK.

Throw exception, but json response get status SUCCESS

I have this part of code in Controller, but when i make this action and IF works fine and the error message appears in console log.
But it looks like 'success' has status true. And it shouldn't
Try {
if ($last['date']) {
if ($last['date']->format('d-m-Y') == $par['date']) {
throw new \Exception('error', 500);
}
}
return new JsonResponse([
'success' => true,
'data' => $content,
'message' => 'success'
]);
} catch (\Exception $exception) {
return new JsonResponse([
'success' => false,
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
]);
}
JQuery
$.ajax({
type: "POST",
url: "/app/url",
data: TableData,
dataType: "json",
success: function(response){
console.log(response.message);
$('#message').html('<p class="alert alert-success">' + response.message + '</p>');
},
error: function (response) {
console.log(response.message);
$('#message').html('<p class="alert alert-danger">' + response.message + '</p>');
}
});
Your AJAX code is receiving the response as success every time, regardless of the JSON content, because you're always sending a 200 response (which is success). To tell AJAX to process the response as an error (and go to the error method instead of success method in your AJAX response handler), you need to send an error code in the response, i.e. 400, like this:
return new JsonResponse([
'success' => false,
'code' => 400,
'message' => $exception->getMessage(),
], 400);
So, if you're throwing your custom Exceptions, you need to set the code property for each according to their real HTTP meaning.
Now, the success and error handlers in AJAX have different parameters. In success, the first parameter is data, simply the data returned from the server. On the other hand, in error, the first parameter is an jqXHR object. To access the data in this object, you have a handful of different parameters, but what you need now, since you have JSON, is jqXHR.responseJSON. So, now your error message will be in response.responseJSON.message, not in response.message. See more about this here.

Getting "Invalid format" error during server side auth in Oauth.io

I have a javascript client and a laravel backend and I am using Oauth.IO for social authentication. I followed the steps specified here: http://docs.oauth.io/#authorizing-the-user-with-both-front-end-and-back-end-sdks
I successfully got state token by calling generateStateToken() method, but when I send that to $this->oauth->auth() method I get Invalid Format error. Can you please tell me what this error means and what I am doing wrong.
Client Side
var selectedAuth = 'facebook';
$.post('http://localhost/auth/v1/social', {provider: selectedAuth, get_state_token: 1}, function(data){
OAuth.popup(selectedAuth)
.done(function(result) {
console.log(result);
$.post('http://localhost/auth/v1/social', {provider: selectedAuth, code: data.token, access_token: result.access_token}, function(data){
console.log(data);
}, 'json');
})
.fail(function (err) {
//handle error with err
});
}, 'json');
Server Side
// code to get the state token in a different method
$token = $this->oauth->generateStateToken();
return response()->json(['status' => 'success', 'token' => $token]);
-- snip --
// code to get access token from state token in another method
$provider = 'facebook';
$request_object = $this->oauth->auth($provider, array(
'code' => $code
));
$credentials = $request_object->getCredentials();
I have verified that $code does have the exact state token that I have received on the 1st step.
The value of $credentials is as follows:
{"status":"error","data":{"code":"Invalid format"},"refreshed":false}
Please help me out here. This error occurs for both for facebook and twitter as well. Let me know if you need more details.
I am really sorry for posting this question. I had missed a step in the documentation. I am leaving this question here as a reference for others in case anyone else faces the same issue.
The error was in my javascript code. While calling Oauth.popup(), I needed to pass the state token and get a code which was then supposed to be passed to the server. I was sending the state token to the server directly instead of the code.
The correct code will be this :
var selectedAuth = 'facebook';
$.post('http://localhost/auth/v1/social', {provider: selectedAuth, get_state_token: 1}, function(data){
OAuth.popup(selectedAuth, {
state: data.token
})
.done(function(result) {
console.log(result);
$.post('http://localhost/auth/v1/social', {provider: selectedAuth, code: result.code, access_token: result.access_token}, function(data){
console.log(data);
}, 'json');
})
.fail(function (err) {
//handle error with err
});
}, 'json');

Error on xmlrpcresp Object

I'm working on a project that I write a Firefox addon to communicate with a service on my client server. My add send a POST request and then the server encounter an error with xmlrpcresp Object that is:
Error: xmlrpcresp Object
(
[val] => 0
[valtyp] =>
[errno] => 6
[errstr] => No data received from server.
[payload] =>
[hdrs] => Array
(
)
[_cookies] => Array
(
)
[content_type] => text/xml
[raw_data] =>
)
and my addon request (it intend to recieve json data from the server):
Request({
contentType: "application/x-www-form-urlencoded",
headers: {
"Keep-Alive": (model.get("interval1") || 30) - 10
},
content: content,
url: url,
onComplete: function(res){
var response = res || this.response;
logger.logFile("collect steps status " + helper.getStatusData(response.json))
if (response.status == "200"){
var json = response.json;
logger.object(json, "track download id");
if(json.results && json.results.status == "0")
callback(json);
else{
if(fallback) fallback(json);
}
}
else{
if(fallback) fallback(json);
}
}
}).post()
The client's IT team said that it might be a header error and this not always happen, just sometime.
Can my above request cause the error? Or, it's just some server side process's error?
"No data received from server" is not an error message that the browser gave you, it is the response from the xmlrpc library on the server. In other words, your add-on successfully sent a request to the server and received a response. In the response the server indicates that its RPC call failed. How could this be a client problem? It is quite obviously a problem with the server that the RPC call went to - instead of giving a response back it returned 200 OK without any data which is what the error message is saying.

Categories