Django returning status code 400 with error message from view - ajax

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;
});

Related

Alert not showing when I do a passed response

$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

Unhandled Rejection (TypeError): Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body

Unhandled Rejection (TypeError): Failed to execute 'fetch' on
'Window': Request with GET/HEAD method cannot have body.
Getting the above error.
export const checkMobile = mobile => {
return ajax(`/mobiles/search`, { method: "GET", body: mobile });
};
function ajax(uri, options = {}) {
const defaultOptions = getDefaultOptions();
options.method = options.method ? options.method : defaultOptions.method;
if (!options.formType) {
options.headers = options.headers
? options.headers
: defaultOptions.headers;
}
options.credentials = options.credentials
? options.credentials
: defaultOptions.credentials;
if (options.body && !options.formType) {
options.body = buildParam(options.body);
}
uri = uri.startsWith("/") ? uri : "/" + uri;
console.log(`${CLIENT_URL}${uri}`);
return fetch(`${CLIENT_URL}${uri}`, options).then(data => data.json());
}
Why I have not been allowed to add body data. Now how will I pass the data to the back end. I am using react in front end.
Check your options object and ensure body is undefined if you're using GET.
GET requests should not be posting any data in the body. If you plan on sending data, you probably want to use POST as the method.

Express.js res.render not redirecting, just displayed in console

This time I want to use res.render to display html as success of DB update. I did it several times, but this time it doesn't work. It's not render html file, just displayed on chrome's console.
I think it caused because of async problem or duplicated response. I tried to many ways but I couldn't solve it, so pointers appreciated.
The code is related when the user paid service, increase user's level.
Get Access Token => Validate => res.render
app.post('/payment/validate', function(req, res, next){
// Get access token
request.post({
url : 'https://payment-company/get/token'
}, function(err, response, body) {
if(!err & response.statusCode == 200) {
var result = JSON.parse(body);
var accessToken = result.response.access_token;
// Validate payment (compare paid and would be paid)
request.get({
headers : { 'Authorization' : accessToken }
url : 'https://payment-company/find/paymentid'
}, function (err, response, body) {
if (!err && response.statusCode == 200){
var result = JSON.parse(body);
if (result.response.amount == req.body.price){
Members.findOne({id : req.user.id}, function(err, member){
// If no problem, update user level
member.level = 2;
member.save(function(err, result){
if (err) return next();
res.render('payment.view.result.ejs',
{
title : 'Success !',
description : 'level up.'
});
});
});
}
} else {
...
}
});
}
})
});
sorry to verbose code I tried to shorten code, No problem until res.render, res.render will work but it's not display page instead it just send html code to chrome's console.
Looks like there's a bit of a misunderstanding of how these requests work. What I think you intend:
Browser makes a GET request, server responds with an HTML document, the browser renders it
User takes an action
Browser makes a POST request, server responds with an HTML document, the browser renders it
What you've started coded on the frontend is an alternate method:
You make a POST request via AJAX, server responds with some JSON, you modify the current document with JavaScript to let the user know

how to make a middleware based on koa, which is used for Intercept HTTP response?

My project base on koa,I want to intercept HTTP response,when the response's message is "no promission",then excute 'this.redirect()'.
Your middleware (interceptor in my example) can access the response body after it yield next, so just place your logic after it yields.
var route = require('koa-route');
var app = require('koa')();
var interceptor = function*(next) {
// wait for downstream middleware/handlers to execute
// so that we can inspect the response
yield next;
// our handler has run and set the response body,
// so now we can access it
console.log('Response body:', this.body);
if (this.body === 'no promission') {
this.redirect('/somewhere');
}
};
app.use(interceptor);
app.use(route.get('/', function*() {
this.body = 'no promission';
}));
app.listen(3001, function() {
console.log('Listening on 3001...');
});

AJAX Request gets cancelled with AngularJS and Spring Security

We're running an external Grails server-application with the Spring Security plugin.
The front-end is running locally on AngularJS.
Whenever I try to login, the request is immediately canceled.. Remarkably AngularJS sends a GET request first with the OPTIONS method; this returns a 200 OK response just fine.
The actual POST request does never reach the server though... what could possibly cancel my request?
The following code:
$scope.login = function() {
$http.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
$scope.loggingIn = true;
// Setup Config
var data = {
j_username: $scope.user.email,
j_password: $scope.user.password
}
var config = {method: 'POST', url: serverUri+'/j_spring_security_check/', data: data};
// Dispatch HTTP Request
$http(config)
.success(function(data, status, headers, config) {
if (data.status) {
// successful login
User.isLogged = true;
User.username = data.username;
}
else {
User.isLogged = false;
User.username = '';
}
$scope.loggingIn = false;
console.log("NOICE!");
})
.error(function(data, status, headers, config) {
$scope.loggingIn = false;
User.isLogged = false;
User.username = '';
if (status == 0) {
// Request got cancelled
console.log("Request got cancelled.");
return;
}
});
}
This is what the canceled request looks like: http://i.stack.imgur.com/kiWnb.png
This is what the OPTIONS request looks like: http://i.stack.imgur.com/FAj96.png
Apparently Chrome does not handle 302 Moved temporarily status codes efficiently when queried by AngularJS in my situation. Firefox properly shows there is a response where Chrome just shows the request as canceled with no response information whatsoever.
This question is solved, but there is still a mystery as to WHY AngularJS does not work. See my question here:
AngularJS $http ajax does not follow Location header

Resources