In my go http handler function response to ajax request, I'd like to send an error message like this:
func AddBlogPOST(w http.ResponseWriter, r *http.Request) {
//process request
if everythingIsOk(r) {
w.Write([]byte("ok"))
return
} else {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("not enough credit"))
return
}
The ajax request is like this:
$(document).on('click', '#submit', function (e) {
$.ajax({
url: '/blog/',
type: 'post',
data: $('.form').serialize(),
success: (res) => {
console.log('success body:', res);
console.log(res);
},
error: (err) => {
console.log('an error occured:', err);
}
});
}
});
It works fine when the reuqest is successful and I get success body: ok
in the browser console. However when there is an error, I get an object like:
readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
abort: ƒ (e)
always: ƒ ()
catch: ƒ (e)
done: ƒ ()
fail: ƒ ()
getAllResponseHeaders: ƒ ()
getResponseHeader: ƒ (e)
overrideMimeType: ƒ (e)
pipe: ƒ ()
progress: ƒ ()
promise: ƒ (e)
readyState: 4
responseText: "credit not enough"
setRequestHeader: ƒ (e,t)
state: ƒ ()
status: 401
statusCode: ƒ (e)
statusText: "Unauthorized"
then: ƒ (t,n,r)
How can I extract "credit not enough"
from this object?
The argument named err
in your error
handler is the jqXHR object. To retrieve the error message you return from your server side code you need to access the responseText
property of that object manually. Try this:
error: (jqXHR) => {
console.log('an error occurred:', jqXHR.responseText);
}