Vuejs won't let me console.log within request - javascript

In the methods section of my Vue.js script im trying to do a console.log but nothing is happening, in fact i can do no javascript at all within this section but the request to '/register' remains working.
postRegister: function(){
//code here works fine
console.log('working')
this.$http.post('/register', this.user, function(response){
//Any code here does not work even though the request itself has worked
console.log('not working');
});
}
My Controller
public function Register(Request $request)
{
$validator = Validator::make($request->all(), [
'username' => 'required|unique:users|max:12',
'email' => 'required|unique:users|email',
'password' => 'required|confirmed'
]);
if ($validator->fails()) {
return $validator->errors()->all();
}
}
As i originally said, everything works the validator returns the correct responses and everything and the post attempt is made successfully, there is no console data being logged however within the http post request!

Since you are using the validator you're not getting back a 200 status code and that's why the success function will not get triggered. You should catch the error and then console.log it:
this.$http.post('/register', this.user)
.then(function(response){
console.log(response);
})
.catch(function(error){
console.log(error);
});

Related

Unable to customize form errors because server is returning 422 Unprocessable Entity without returning errors

I'm working with Laravel and VueJS and for all of my post and put methods server returns the newly created data after submitting the form, in the case of errors, I cannot access them from the browser console. This is what I can see in the newtwork tab.The purpose is to customize form errors according to errors that is being returned by the server
Here is my backend code :
private function validateForm($data){
return Validator::make($data,
[
'fname' => ['required', 'string','min:2' ,'max:255'],
'lname' => ['required', 'string','min:2' ,'max:255'],
// 'mname' => ['string','min:2' ,'max:255'],
'company' => ['string','min:2' ,'max:255'],
'title' => ['string','min:2' ,'max:255'],
'phone_number' => ['string','min:13' ,'max:13'],
'city' => ['required', 'string','min:2' ,'max:100'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed']
// 'password_confirm'=>['required','string']
]
)->validate();
}
//Register
public function register(Request $request){
$data=$this->validateForm($request->all());
$data['password']=Hash::make($data['password']);
$user=new User($data);
$user->save();
return response()->json($user);
}
And my code from the front-end:
export default{
data(){
return {
form:{
email:'',
password:'',
password_confirmation:'',
fname:'',
lname:'',
city:''
},
formError:''
}
},
methods:{
//This should be a POST method through axios
register:async function(){
try{
const res=await axios.post('api/register',
{
email:this.form.email,
password:this.form.password,
password_confirmation:this.form.password_confirmation,
fname:this.form.fname,
lname:this.form.lname,
city:this.form.city
});
//Une fois inscrit,il est redirige vers la page de login
this.$router.push({path:'/login'});
console.log("My data : ",res.data);
}catch(err){
console.log("Errors",err);
}
}
}
}
When there are no errors, everything goes fine, but when there are errors, this is what I get in the browser console tab:
And in the Devtools network tab
I've tried the following link Issues with Axios catch method from Laracast
how to display the errors in .catch coming from an api on frontend
And some others solution,but all of them didn't solve my problem.
Before using async-await pattern i used axios.post('url',data).then(res=>...).catch(err=>...)
When i use postman,http status is still 422 but the error object is returned,so with postman everything goes fine but not in the browser
How can i solve this problem?
Laravel returns the HTTP 422 - Unprocessable Entity when the validations you set fail. In your case I would take a closer look at the data you're posting to the server and manually check if it passes the validation cases you wrote.
To get the exact fields that are causing the error you need to handle this in your code, like this for example:
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
// 500 is the HTTP Status Code you want to return.
// This should also throw you in the catch branch of your front-end code
return response()->json(['errors'=>$validator->errors()], 500);
}
In your code the $data variable from the register function should be checked if it fails validation and return the error
This is because err will return the toString() method when accessed directly, but has properties:
err.response.data will have what you're looking for.
When there's an HTTP error (e.g. a response code between 400 and 599) axios returns an axios error response and in the repository documentation under error handling it indicates that you can access the actual response using error.response.data. For example:
try {
const res=await axios.post('api/register',
{
email:this.form.email,
password:this.form.password,
password_confirmation:this.form.password_confirmation,
fname:this.form.fname,
lname:this.form.lname,
city:this.form.city
});
//Une fois inscrit,il est redirige vers la page de login
this.$router.push({path:'/login'});
console.log("My data : ",res.data);
}catch(err){
if (err.response && err.response.status === 422) {
if (err.response.data.errors.fname) {
console.log('First name errors: '+ err.response.data.errors.fname.join(','));
}
// and so on
}
}
When Axios throws an error, the HTTP response can be found in error.response. Validation errors will be in the errors key, so you can access validation errors like this:
axios.post(someUrl, someData)
.then(response => {
// Successful response
})
.catch(error => {
let errors = error.response.data.errors;
});

Implementing a custom ember-simple-auth Authenticator

Firstly, I am not a seasoned JS Developer, so please excuse obvious mistakes that I could have made.
I am trying to implement a custom Authenticator for authenticating a user with Keycloak using the OAuth2 Password Grant which requires the client_id be passed as part of the request body.
import OAuth2PasswordGrant from 'ember-simple-auth/authenticators/oauth2-password-grant';
export default OAuth2PasswordGrant.extend({
serverTokenEndpoint: 'http://localhost:8080/something/token',
makeRequest(url, data, headers = {}) {
data.client_id = 'my-app';
return this._super(url, data, headers);
}
});
I have a controller that uses this Authenticator by calling this action:
actions: {
authenticate() {
let {username, password} = this.getProperties('username', 'password');
this.get('session').authenticate('authenticator:oauth2', username, password).then(() => {
// Do something
}).catch((response) => {
// Show error
});
}
}
This causes Firefox to hang and gives me an unresponsive script message.
If I remove the return from the makeRequest() method, I can see from the browser debugger that the call to Keycloak actually returns correctly with the object that contains my token etc. However ember inspector shows some errors related to unresolved promises. But I guess that's because I'm no longer returning the promise.
What am I doing wrong here?
How can I fix the unresponsive script issue?
Is there another way for me to achieve my goal?
Edit 1: This is when I remove the return
Here is the actual object that is returned:
{
"access_token":"eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJTRUNSd09fMlZWdGhxUVBUWnFxNHlqX0tKekxnOElSTjBrQkx5UTlacklrIn0.eyJqdGkiOiI1NDgzZDdkMi0zMDdhLTQyZjItYWUxZC0xYTZjMTZjOTM2ZjAiLCJleHAiOjE1MDgzMzE5MjAsIm5iZiI6MCwiaWF0IjoxNTA4MzMxNjIwLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvc2Z4LWl0cmFuc2Zlci13ZWItYWdlbnQiLCJhdWQiOiJhZ2VudC13ZWItYXBwIiwic3ViIjoiMzZiMWY4OWMtNGYwMC00OTU1LWE0YzMtZWQ0NzZmZDU2OGM3IiwidHlwIjoiQmVhcmVyIiwiYXpwIjoiYWdlbnQtd2ViLWFwcCIsImF1dGhfdGltZSI6MCwic2Vzc2lvbl9zdGF0ZSI6IjQwODMxZWFhLTRmMmEtNDk2ZS05ND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aWF0IjoxNTA4MzMxNjIwLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvc2Z4LWl0cmFuc2Zlci13ZWItYWdlbnQiLCJhdWQiOiJhZ2VudC13ZWItYXBwIiwic3ViIjoiMzZiMWY4OWMtNGYwMC00OTU1LWE0YzMtZWQ0NzZmZDU2OGM3IiwidHlwIjoiUmVmcmVzaCIsImF6cCI6ImFnZW50LXdlYi1hcHAiLCJhdXRoX3RpbWUiOjAsInNlc3Npb25fc3RhdGUiOiI0MDgzMWVhYS00ZjJhLTQ5NmUtOTQ1ZC03YmViMTdlNDZlNDQiLCJyZWFsbV9hY2Nlc3MiOnsicm9sZXMiOlsidW1hX2F1dGhvcml6YXRpb24iLCJiYWNrLW9mZmljZS1hZ2VudCJdfSwicmVzb3VyY2VfYWNjZXNzIjp7ImFjY291bnQiOnsicm9sZXMiOlsibWFuYWdlLWFjY291bnQiLCJtYW5hZ2UtYWNjb3VudC1saW5rcyIsInZpZXctcHJvZmlsZSJdfX19.XgYSZWwfaHeY1yZZuwnQ5bj-0IHP4UEmiPTqaeCE1KVyjl3kZz3HJVisndtcKPr05kalS-M_NqU0TaYvbcZ_zesJRIga5sz4gGRqObUmUCUJoQ_iWoOhbM2SutiVnlfgJDACvOxegIcSvakZTgQsEcSweio_0kMFqi-2DYzFp6Rl0TpQ8vALLkc7rEOonUGyt7S4qQzkT-xB1_ZDlSVfm6mC-QKYNZhtqBT18P7MKxBhEgwrJtCytA_4ft7qNAbgvZ3kUohcbhzxGvtHej5RKHNI2wTzwK3IWHbkLWNndxSk_Lzj2-lCx380VpTkVpiDJfq5umjskOmI13dyPF7paA",
"token_type":"bearer",
"not-before-policy":0,
"session_state":"40831eaa-4f2a-496e-945d-7beb17e46e44"
}
This is what ember inspector (Promises) shows:
Here is the stacktrace from the Promise:
Ember Inspector ($E): authenticate/<#http://localhost:4200/assets/vendor.js:77927:9
initializePromise#http://localhost:4200/assets/vendor.js:63591:7
Promise#http://localhost:4200/assets/vendor.js:64067:35
authenticate#http://localhost:4200/assets/vendor.js:77919:14
authenticate#http://localhost:4200/assets/vendor.js:78528:14
authenticate#http://localhost:4200/assets/vendor.js:79420:14
authenticate#http://localhost:4200/assets/sfx-itransfer-web-agent.js:855:9
join#http://localhost:4200/assets/vendor.js:20249:24
run$1.join#http://localhost:4200/assets/vendor.js:37657:12
makeClosureAction/</<#http://localhost:4200/assets/vendor.js:29073:16
exports.flaggedInstrument#http://localhost:4200/assets/vendor.js:37087:14
makeClosureAction/<#http://localhost:4200/assets/vendor.js:29072:15
submit/<#http://localhost:4200/assets/vendor.js:70453:20
tryCatch#http://localhost:4200/assets/vendor.js:63549:14
invokeCallback#http://localhost:4200/assets/vendor.js:63562:15
publish#http://localhost:4200/assets/vendor.js:63532:9
#http://localhost:4200/assets/vendor.js:54458:16
invoke#http://localhost:4200/assets/vendor.js:19948:17
flush#http://localhost:4200/assets/vendor.js:19827:25
flush#http://localhost:4200/assets/vendor.js:20019:25
end#http://localhost:4200/assets/vendor.js:20128:26
run#http://localhost:4200/assets/vendor.js:20212:21
join#http://localhost:4200/assets/vendor.js:20219:24
run$1.join#http://localhost:4200/assets/vendor.js:37657:12
handleEvent/<#http://localhost:4200/assets/vendor.js:58233:18
exports.flaggedInstrument#http://localhost:4200/assets/vendor.js:37087:14
handleEvent#http://localhost:4200/assets/vendor.js:58232:17
_Mixin$create.handleEvent#http://localhost:4200/assets/vendor.js:57385:12
_bubbleEvent#http://localhost:4200/assets/vendor.js:57685:14
setupHandler/<#http://localhost:4200/assets/vendor.js:57619:20
dispatch#http://localhost:4200/assets/vendor.js:5546:16
add/elemData.handle#http://localhost:4200/assets/vendor.js:5355:6
Actually you solution looks like right.
I guess you have a problem in server response or mismatch request methods GET/POST. To solve this try to debug promise inside makeRequest.
return new RSVP.Promise((resolve, reject) => {
fetch(url, options).then((response) => {
response.text().then((text) => { //<-- here debug text
let json = text ? JSON.parse(text) : {};
if (!response.ok) { //<-- and here debug response
response.responseJSON = json;
reject(response);
} else {
resolve(json);
}
});
}).catch(reject);
So if problem will here, just rewrite whole method of makeRequest and add you own promise with custom fetch.
Another way is to write custom Authenticator, overriding authenticate, restore and (optionally) invalidate methods as wrote in documentation: https://github.com/simplabs/ember-simple-auth#implementing-a-custom-authenticator

Issues retrieving fbsdk Access Token and User ID

I am trying to retrieve the Access Token and User ID of the logged in user in my React Native App. For some reason when I tried to update the fbsdkcore package, it did not exist anymore. So, I tried to resolve it within the general fbsdk package.
I am calling the js file (of which I think retrieves the accesstoken) in the package as:
const AccessToken = require('react-native-fbsdk/js/FBAccessToken');
And subsequently in my code I try to log it so that I can see if it works, simply by:
console.log(AccessToken.getCurrentAccessToken());
console.log(AccessToken.getUserId);
But the log only returns:
2016-05-05 10:22:28.276 [info][tid:com.facebook.React.JavaScript] { _45: 0, _81: 0, _65: null, _54: null }
2016-05-05 10:22:28.277 [info][tid:com.facebook.React.JavaScript] undefined
Which does not seem to be the droids that im looking for.
I inspected the code for the js file in the fbsdk package and the getCurrentAccessToken code looks like this:
/**
* Getter for the access token that is current for the application.
*/
static getCurrentAccessToken(): Promise<?FBAccessToken> {
return new Promise((resolve, reject) => {
AccessToken.getCurrentAccessToken((tokenMap) => {
if (tokenMap) {
resolve(new FBAccessToken(tokenMap));
} else {
resolve(null);
}
});
});
}
Which of course seems reasonable. But since I get this really weird result when I try to call it, I get worried over that I have done something wrong in the bigger picture. I even modified the resolve(null) part of the code so that I could make sure of what happend. But it still returned the same weird "token".
The log also returns this error when logging in:
2016-05-05 10:22:07.630 AppName[15097:415865] -canOpenURL: failed for URL: "fbauth2:/" - error: "(null)"
But I think that is only because I don't have the facebook app on my xcode simulator.
Can anybody throw me a good guess on what I have done wrong??
GetCurrentAccestoken returns a promise.
Maybe you can try:
AccessToken.getCurrentAccessToken().then(
(data) => {
console.log(data.accessToken.toString())
}
)
Try this. It worked for me
AccessToken.getCurrentAccessToken().then(
(data) => {
console.log(data.accessToken)
console.log(data.userID);
});
LoginManager.logInWithReadPermissions(['public_profile']).then(
function (result) {
if (result.isCancelled) {
alert('Login cancelled');
} else {
// alert('Login success with permissions: ' +
// result.grantedPermissions.toString());
AccessToken.getCurrentAccessToken().then(
(data) => {
doLoginViaFb(data.userID, data.accessToken);
}
);
alert(result);
console.log(result.toString());
console.log(JSON.stringify(result));
}
},
function (error) {
alert('Login fail with error: ' + error);
}
);

AngularJS $http.post call returning 502 (bad gateway) error

I am developing websites where I am using AngularJS in frontend and Laravel php framework in backend.
I have one simple form that is sending $http.post call to laravel backend and there are data processed and email is sended.
Everything works fine on my local Apache server but on online on webhosting server it returns 502 (bad gateway error) in developer console (see screenshot below).
Screenshot: http://s32.postimg.org/bwnxyps1x/502.jpg
And yet, when this error appears, script in backend is executed and email is sended. It is really weird.
In AngularJS I have simple factory that is sending $http.post call...
var sendForm = function sendForm($http) {
return {
sendForm: function($scope) {
return $http({
method: 'POST',
url: '/odeslat',
data: {titul: $scope.form.titul, jmeno: $scope.form.jmeno, prijmeni: $scope.form.prijmeni, email: $scope.form.email,
telefon: $scope.form.telefon, zprava: $scope.form.zprava, human: $scope.form.human}
});
}
}
};
module.exports = sendForm;
This is my controller.
var formularCtrl = function formularCtrl($scope, sendForm) {
$scope.form = {};
$scope.form.human = 'Jsem člověk.';
var odeslano = false;
$scope.submitForm = function submitForm(isValid) {
$scope.showErrorMessage = false;
$scope.errorMessage = "";
if((isValid) && (!odeslano))
{
sendForm.sendForm($scope).success(function(data){
if (!data.success) {
// if not successful, bind errors to error variables
$scope.errorMessage = data.message;
$scope.showErrorMessage = true;
} else {
// if successful, bind success message to message
$scope.message = data.message;
$scope.showMessage = true;
odeslano = true;
}
});
}
else
{
$scope.showErrorMessage = true;
$scope.errorMessage = "Doplňte prosím všechny povinné údaje. ";
}
}
};
module.exports = formularCtrl;
And finally this is just simple method in laravel controller.
public function sendForm(Request $request) {
$v = Validator::make($request->all(), [
'jmeno' => 'required'
]);
if($v->passes()) {
$input = $request->all();
$this->sendMessage($input);
return response()->json(['success' => true, 'message' => 'Formulář byl odeslán. Jakmile to bude možné, budete kontaktováni.']);
}
elseif($v->fails())
{
$input = $request->all();
return response()->json(['success' => false, 'message' => 'Musíte doplnit povinné údaje']);
}
}
private function sendMessage($input)
{
Mail::send('emails.formular', $input, function($message)
{
$message->from(self::FROM, self::SUBJECT);
$message->to(self::TO);
});
}
I am not expert on AngularJS and I am really confused by this error. Do you have any suggestions – what can be the cause?
Thank you very much! All tips are appreciated.
502 indicates the server could not complete something properly. So it is sending out an e-mail, but maybe it tries to something after that script like update a DB. As your local is working OK and your remote is working partially OK this boils down to some server issue, is it possible there is more logging on this server that can tell us why the 502 is being issued. Perhaps the e-mail program returns this after attempting to send the e-mail?
It seems just like backend doesn't send anything back to your angular app. It should response with OK (200 for example) HTTP status.
Okay. So I have contacted webhosting provider and they turned off OPcache in htaccess and it is working now... :)

Catching errors in AngularJS when using $resource

Searching product is working fine when product is found, but if user search with letters, or bad criteria, nothing happens. I can see the error message in JavaScript-console and in Header there is Status Code 204, no Content. I think that Angular is just working badly, when empty object is coming back. How can I tell an user that there is no products with his/her criteria, cause I can't catch the error message at all at the moment. What is the correct and best solution to handle this? Catching errors or solving that result was empty and showing an error message in HTML-page?
Service:
return $resource(
'http://localhost:8080/RMAServer/webresources/com.rako.entity.jdeserials/:id',
{},
{
get: { method: 'GET',isArray:false, params: {id: '#serial'} },
update: { method: 'PUT', params: {id: '#serial'} }
});
Controller
//Searching product with serial number/LOTN
$scope.searchProduct = function () {
$scope.serials = lotnSvc.get({id: $scope.serial}).$promise.then(
function (data) {
var litm = data.litm;
productSvc.get({id: litm}, function (product) {
$scope.product = product;
getBrands();
},function(error){
alert('ERROR when searching product');
console.log("error---->" + error);
});
},function(error){
alert('ERROR when searching product');
console.log("error---->" + error);
});
};
Error message in javaScript console
Error: [$resource:badcfg] Error in resource configuration for action `get`. Expected response to contain an object but got an array
http://errors.angularjs.org/1.3.15/$resource/badcfg?p0=get&p1=object&p2=array
at REGEX_STRING_REGEXP
Status code in Header
Just try to send the success and the error handlers as second and third parameters to "get" function instead of using promises. There was the same problem: How to handle $resource service errors in AngularJS

Categories

Resources