Alert not showing when I do a passed response - laravel

$bd = Carbon\Carbon::now()->diffInYears(Carbon\Carbon::parse(request()->input('form.birthdate');
if ($bd <= 6){
return response(['message' => "That's less than 6, not allowed",500]);
}
and in my axios request
}).then(response => {
if (response.status === 500 ){
alert(error.response.data.message);
}
else {
window.location.replace("/admin/users/"+this.user.id);
}
I don't know why my alert not showing there. iT sucks?

How i handle axios is below
First return your response from laravel like this. (Include the status code)
return response(['message' => "That's less than 6, not allowed"], 400);
After that on your axios side get the message like this
axios.post().then(function(response){
// this will run if the status code is 200 in laravel response
// Get passed data like 'response.data.message', You will get your passed values after 'response.data'
}).catch(function(error){
notify('error', error.response.data.message); // You will get your passed values after 'error.response.data'
})
The catch function will run when your ajax response is 400 500 etc etc

Modify your response as follows:
return response(['message' => "That's less than 6, not allowed"], 500);

Parmeters for the response helper are response(string message, int status_code, array? headers)
If you wan't return json use
return response()->json(array json, int status_code, array? headers)
For more informations see the documentation https://laravel.com/docs/7.x/helpers#method-response

Related

How do I get a specific column name values using Axios Promise-based Http Request in Vue.js and Laravel 8

If I do this in my Vue.js script component
getResumeAPIData(id){
// declare a response interceptor
axios.interceptors.response.use((response) => {
// do something with the response data
console.log('Response was received');
return response;
}, error => {
// handle the response error
return Promise.reject(error);
});
// sent a GET request
axios.get(`api/resume-data-returns/${id}`)
.then((response)=>{
this.RelationTable = response.data
console.log(this.RelationTable);
})
},
I get a response like this
{"id":1,"name":"userlocalvm","email":"userlocalvm#v","email_verified_at":null,"type":"user","bio":"Why","photo":"1606931001.jpeg","created_at":"2020-12-02T16:01:00.000000Z","updated_at":"2020-12-02T17:43:21.000000Z"}
Because of my Laravel api.php->Controller Backend code
$findOrFailId = Resumes::findOrFail($forEachId);
$foreignKeyOfResTable = $findOrFailId->user_id;
return User::findOrFail($foreignKeyOfResTable);
But if I do it like this as
// sent a GET request
axios.get(`api/resume-data-returns/${id}`)
.then((response)=>{
this.RelationTable = response.data.created_at
console.log(this.RelationTable);
})
The added dot then the property name of the column
response.data.created_at
I get a response
undefined
Sorry if this is a silly question as I am still quite a rookie in programming in general and the jargons that comes with it and I want learn and master javascript and php so bad!
It might be that the response is inside another data object. You might have to do something like this:
response.data.data.created_at

Handling REST API server response

I've been working with REST API CodeIgniter for more than a year and usually when I want to return any response I will return 200 for all kind of request. I know that there are status code provided for all response but I am actually quite wondering, is it wrong if I use 200 for all response? And determine the data status with true and false.
Here is the sample code that I always use. Let's say to check whether the user is exist or not.
CodeIgniter REST API
$user = [ 'id' => 1, 'name' => 'John Doe' ];
$this->response([
'status' => !empty($user) ? true : false,
'user' => $user
], REST_Controller::HTTP_OK);
React Native
try {
const res = await axios.get('https://www.example.com/retrieve-user?user_id=3');
if (res.status == 200){
if(res.data.status == true){
// user found
} else {
// user not found
}
} else {
alert('Internal server error.')
}
} catch (err) {
console.error(err);
}
Based on the example, I am actually depending on the status code 200 to determine if there is an error in the server (code error, invalid request, etc).
So my question is, is it okay to stick with this method?
Given your API, yes handling code 200 seems enough as your API might not return any other HttpCode.
Given a bigger API (even simple), no.
Your API might return a 204/404 if no user if found with given id.
Your API might return a 503 if your API is under deployment (and unavailable) or under maintenance, and you may retry 30 seconds later.
Your API might reject request if a given header is missing (Content-Type ...) and return a 400...
EDIT 1 :
if (res.status == 200){
// user found
} else if (res.status == 204) {
// user not found
} else {
alert('An error occured')
}

Why does flutter's http.get function make the server return http error code 409? Invoking the exact same url on the browser returns status code 200

My Flutter method that makes the http request. It even prints out the http url and invoking this same exact url on the browser returns status code 200 yet calling it programmatically using flutter's http.get returns error code 409.
Future<String> saveUser(String firstName, String lastName, String sex) async {
String url = domain +
'register?' +
'first_name=' +
firstName +
'&last_name=' +
lastName +
'&sex=' +
sex;
final response = await http.get(url);
print(url);
print(response.statusCode);
print(response.body);
if (response.statusCode == 200) {
// If server returns an OK response, parse the JSON.
return response.body;
} else {
// If that response was not OK, throw an error.
return 'Failed to Register User';
}
}
This is flutter's console log. the number represents the error code, and the 'script' tags represent the response body
I/flutter (27919): http://filteredkenya.co.ke/baliach/register?first_name=Tyler&last_name=Mutai&sex=Male
I/flutter (27919): 409
I/flutter (27919): <script>document.cookie = "humans_21909=1"; document.location.reload(true)</script>
This is my Laravel's Controller method that's supposed to save data to DB and return a response (Has been mapped to both get and post methods):
public function register(Request $request)
{
$data = $request->all();
//Validation:
$validator = Validator::make($data, [
'first_name' => 'required|string|min:3',
'last_name' => 'required|string|min:3',
'sex' => 'required|string|min:3',
]);
//If there is an error in either one of the inputs
if ($validator->fails()) {
return response()->json($validator->errors());
}
$registration = new Registration;
$registration->first_name = $data['first_name'];
$registration->last_name = $data['last_name'];
$registration->sex = $data['sex'];
$registration->save();
return response()->json($data);
}
Turns out that my home wifi network is in some way resulting to an error 409 on the server. Testing the app on a different network yields correct results (Http Status Code 200). Why this happens, I'm not really sure.
I have solved the problem by changing the name of the url, if I had register.php I changed it to regis.php this made the variables refresh or something similar and it was solved.

Response from laravel is not logging properly in vue js

I am working on a project. Where I am using laravel as back end and VueJS as front end. I called an API that requests laravel to insert a user. I want to check whether the back end validation is successfully done or not. for this, I'm sending an email that is already in the database. the validation response is all okay. But I want to log a message only instead of logging the whole response. somehow the message is not logging but the response is logging. I could not figure out what the problem is
API call
Response
I want to log the message, not the whole response
Chain the ```.catch(error => { console.log("Errors, error") }); on your ajax request.
I have written this small helper once. It can handle Laravel and also your custom messages returned from the backend. It's not perfect but can get your working in a good direction.
export function errorMessage(error) {
let errorResponse = error.response.data.errors ? error.response.data.errors : error.response.data;
let errors = [];
for (let key in errorResponse){
if(key === 'message'){
errors.push(errorResponse[key]);
}
else if (key !== 'exception' && key !== 'file' && key !== 'line' && key !== 'trace'){
for (let i = 0; i < errorResponse[key].length; i++){
errors.push(errorResponse[key][i]);
}
}
}
return errors;
}
You can use it in your catch block like let errors = errorMessage(error)). I fed my notification plugin with messages that displays on the top of the screen.
So the 422 is an error you will have to handle it in a .catch block
.then() // everything went good
.catch() // something went wrong
Something like this
.then(response => {
// great
})
.catch(error => {
if (error.response.status === 422) {
// do something here
}
}

Django returning status code 400 with error message from view

I have a view that receives a form submit request via ajax. Sometimes it returns bad request based on certain criteria or in case an exception is raised. Now, sending back simple HttpResponse(status=400) is plain simple. Can I send a reason along with it a reason that I can access using xhr.responseText?
If I understand you right, you can return 400 with some context:
context = {
'reason': 'your reason'
}
response = render(request, '400.html', context)
response.status_code = 400
return response
and for cases with ajax, you just return HttpResponse:
context = {
'status': '400', 'reason': 'you can access this view only via ajax'
}
response = HttpResponse(json.dumps(context), content_type='application/json')
response.status_code = 400
return response
and in your js code:
$.ajax({
// ...
// ...
}).fail(function(data){
var status = data.status;
var reason = data.reason;
});

Resources