Why axios does't catch errors from server response? - laravel

i'm using laravel and vue, i use axios to make a request, that request response a json, but if cannot find the data, return a 404,but catch of axios don't work
this is the front code
methods: {
updateData: function () {
axios.post('acd/' + this.number + '/' + this.date)
.then((response) => {
this.setData(response['data'])
}).catch(err => {
console.log("this dont display")
});
setTimeout(this.updateData, 1000)
this.updateDoughnutChart();
this.updateLineChart();
this.updatePieChart();
},
and this is the back code
public function getAcd(Request $request, $id, $date)
{
$dateClient = new Carbon($date);
$dateServer = new Carbon;
if($dateClient->format('Y-m-d') == $dateServer->format('Y-m-d'))
{
$data = App::make('vodia')->getAcd($id);
}
else
{
$data = Call::where('acd', $id)->whereDate('created_at', $date)->firstOrFail();
$data = json_decode($data->data);
}
return response()->json(($data));
}
this is the console error
Uncaught (in promise) Error: Request failed with status code 404

Think the syntax for the catch block is not correct
your code
axios.post('acd/' + this.number + '/' + this.date)
.then((response) => {
this.setData(response['data'])
}).catch(err => {
console.log("this dont display")
});
suppose to be
axios.post('acd/' + this.number + '/' + this.date)
.then((response) => {
this.setData(response['data'])
}).catch((err) => {
console.log(err)
});

Related

Progressive Web Apps laravel cache issue

I am working with PWA for my laravel project, My PWA app working fine, my website run in https only but When i logged in my website shows my old logged user details how can i solve this issue?
I am afraid my website also run based on cache memory
In localhost PWA icon not showing in my browser how can i solve in localhost
here i added service provider js file
// Cache API
const staticCacheName = 'app-shell-v2.0';
const filesToCache = [
// Files
'.',
//css files and js file
];
self.addEventListener('install', event => {
console.log('Installing worker to cache static assets');
self.skipWaiting();
event.waitUntil(
caches.open(staticCacheName)
.then(cache => {
return cache.addAll(filesToCache);
})
);
});
self.addEventListener('activate', event => {
console.log('Activating new worker...');
const cacheWhitelist = [staticCacheName];
self.clients.claim();
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheWhitelist.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
);
})
);
});
self.addEventListener('fetch', event => {
// exclude directories from cache
/*if (event.request.url.match('^.*(\/admin\/).*$','^.*(\/users\/show\/).*$')) {
return false;
}
if (event.request.url.endsWith('authenticate')) {
return false;
}*/
console.log('Fetch event for ', event.request.url);
event.respondWith(
caches.match(event.request)
.then(response => {
if (response) {
console.log('Found ', event.request.url, ' in cache');
return response;
}
console.log('Network request for ', event.request.url);
return fetch(event.request)
.then(response => {
if (response.status === 404) {
return caches.match('https://site_url/404.html');
}
return caches.open(staticCacheName)
.then(cache => {
cache.put(event.request.url, response.clone());
return response;
});
});
}).catch(error => {
console.log('Error, ', error);
return caches.match('https://site_url/offline.html');
})
);
});

Download an image to React Native from a Laravel server?

I am looking to download an image stored on a server into my React Native app.
I had a function that looked like this:
public function image(Request $request, $id)
{
$company = Company::find($id);
$filePath = storage_path() . '/app/' . $company->image;
return response()->file($filePath);
}
And it returned nothing I could read within the app when I tried the following function:
setCompany = async () => {
let company = await AsyncStorage.getItem('currentCompany');
company = JSON.parse(company);
if (company.image !== null) {
let image = await getCompanyPicture({company_id: company.id});
console.log('Here: ', image);
// This is blank, react native returns a warning about data not being of a readable type
}
this.setState({company});
};
I am able to get the image in base_64 using this method:
public function image(Request $request, $id)
{
$company = Company::find($id);
$file_path = storage_path('/app/' . $company->image);
if (file_exists($file_path)) {
$fileData = file_get_contents($file_path);
$fileEncode = base64_encode($fileData);
return response()->json(['status' => 'success', 'data' => ['file' => $fileEncode, 'file_path' => $file_path]]);
}
return response()->json(['status' => 'failure', 'data' => ['file' => null, 'file_path' => $file_path]]);
}
Here is my Axios method too just in case:
export const sendRequest = async (url, data, token, method) => {
let headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Method': 'POST, GET, DELETE, PUT',
};
if (typeof token !== 'undefined' && token !== 'undefined' && token.length) {
headers.Authorization = 'Bearer ' + token;
}
if (method === 'get' && data) {
url +=
'?' +
Object.keys(data)
.map((value) => {
return value + '=' + data[value];
})
.join('&');
data = null;
}
return await axios({
headers: headers,
method: method ? method : 'post',
url: url,
data: data,
})
.then((response) => {
return response;
})
.then((json) => {
return json.data;
})
.catch((error) => {
console.error(error);
if (
error.message !== 'Network Error' &&
error.response.status !== 500 &&
error.response.status !== 413
) {
return error.response.data;
} else if (error.message === 'Network Error') {
return {
status: 'error',
message: 'Unable to connect to server',
};
} else if (error.response.status === 500) {
return {
status: 'error',
message: 'Internal Server Error',
};
} else if (error.response.status === 413) {
return {
status: 'error',
message: 'The file(s) size is too large',
};
} else {
return {
status: 'error',
message: error.message,
};
}
});
};
If anyone could comment on the performance impact of using base_64 instead of the straight file download that would also be helpful
But ultimately I would like a solution for handling the Laravel response()->file() if possible (which I'll use if base_64 is less efficient)
I'm not sure about RN code syntax, but I've ready code with jQuery+poorJS, which looks like this:
$.ajax({
url: "load-image-url", // URL FOR GET REQUEST
cache:false,
xhr: function() { // ACTUALLY THIS PART CAN BE USED AND CUSTOMIZED BY YOU
let xhr = new XMLHttpRequest();
xhr.responseType= 'blob'
return xhr;
},
success: function(data) {
let url = window.URL || window.webkitURL;
$('#image').attr('src', url.createObjectURL(data));
},
error: function(err) {
// console.log(err);
}
}).fail(function() {
$('#ss_product_image').attr('src', "default-image-url.jpg");
});
In my example I've used GET request (but you can try to modify it and test if you want, honestly IDK about that).
This is the back-end part:
public function image(Request $request, $id)
{
// HERE YOU NEED TO GET YOUR IMAGE (using $id or/and $request params) CONTENT FROM SOMEWHERE YOU WANT
$content = <CONTENT>;
return response()->make($content, 200, [
'Content-Type' => (new \finfo(FILEINFO_MIME))->buffer($content),
'Content-length' => strlen($content),
]);
}
I was able to solve this issue by using rn-blob-fetch.
The files are downloaded into a temp cache which can then be accessed for previewing and saving.
this is my function now:
downloadFiles = async (isReply) => {
let {enquiry, reply} = this.state;
this.setState({isLoading: true});
const token = await AsyncStorage.getItem('userToken');
let filePaths = [];
let fileCount = 0;
let files = enquiry.files;
if (isReply) {
files = reply.files;
}
const dirToSave =
Platform.OS == 'ios'
? RNFetchBlob.fs.dirs.DocumentDir
: RNFetchBlob.fs.dirs.DownloadDir;
new Promise((resolve, reject) => {
for (var i = 0; i < files.length; i++) {
var id = files[i].file_id;
var name = files[i].file.file_name;
var ext = extension(name);
const configOptions = Platform.select({
ios: {
appendExt: ext,
fileCache: true,
title: name,
path: `${dirToSave}/${name}`,
},
android: {
useDownloadManager: true,
notification: true,
mediaScannable: true,
fileCache: true,
title: name,
path: `${dirToSave}/${name}`,
},
});
var mime = content(ext);
let headers = {
'Content-Type': mime,
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Method': 'POST, GET, DELETE, PUT',
Authorization: 'Bearer ' + token,
};
RNFetchBlob.config(configOptions)
.fetch('GET', BASE_API + '/enquiries/files/download/' + id, headers)
.then(async (response) => {
RNFetchBlob.fs.writeFile(
configOptions.path,
response.data,
'base64',
);
filePaths.push({
title: configOptions.title,
path: configOptions.path,
ext: extension(configOptions.title),
mime,
});
fileCount++;
if (fileCount >= files.length) {
resolve('Download Successful!');
}
})
.catch((error) => {
console.log('File Download Error: ', error.message);
reject('Download Failed');
});
}
})
.then((data) => {
this.setState({isLoading: false, filePaths});
})
.catch((error) => {
console.log('Download Promise Error: ', error);
this.setState({isLoading: false});
});
};
previewDocument = (id) => {
let {filePaths} = this.state;
if (Platform.OS == 'ios') {
RNFetchBlob.ios.openDocument(filePaths[id].path);
} else if (Platform.OS == 'android') {
RNFetchBlob.android.actionViewIntent(
filePaths[id].path,
filePaths[id].mime,
);
}
};

How to save session() value " " in laravel?

In app.js -> methods i have this.chat.image.push(''); and in axios.post send i have
methods:{
send(){
if(this.message.length != 0)
{
this.chat.message.push(this.message);
this.chat.user.push('');
this.chat.image.push('');
this.chat.time.push('');
axios.post('admin/send', {
message : this.message,
chat:this.chat
})
.then(response => {
// console.log(response);
this.message = '';
})
}
},
getOldMessages(){
axios.post('admin/getOldMessage')
.then(response => {
if (response.data != '') {
this.chat = response.data;
}
})
},
And in mounted() i have
mounted(){
this.getOldMessages();
Echo.channel('chat')
.listen('ChatEvent', (e) => {
this.chat.message.push(e.message);
this.chat.user.push(e.user);
this.chat.image.push('source/admin/assets/images/avatar/'+e.image);
axios.post('admin/saveToSession',{
chat : this.chat
.then(response => {
console.log(response);
})
})
})
}
In Controller i have function saveToSession
public function saveToSession(request $request)
{
session()->put('chat',$request->chat);
}
In send() function i get image=" "; but when I save to the session it returns null, How come it returns to the value = " " ? Thanks
Check that value in $request->chat are coming properly or not if yes then you can try other methods as well
Via a request instance
$request->session()->put('key', 'value');
Via the global helper
session(['key' => 'value']);

RXJS observer retry not a function

I would like to use the retry property of the observer to try 3 times before it gives up and throws an error. However when I run the following code I get 'retry is not a function'. Any ideas what is going on ?
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
this._log.debug('SecureHttpService#get: ' + url);
let resultObservable = Observable.create((observer) => {
this._log.debug('resultObservable');
this.tryReActivateToken().then(
(result) => {
this._log.debug('resultObservable#then#result: ' + result);
if (result === true) {
let headers = new Headers();
headers.append('Authorization', 'Bearer ' + this.access_token);
headers.append('X-Requested-With', 'XMLHttpRequest');
// headers.append('Accept', 'json');
this._log.debug(this.access_token);
let superGetObs = super.get(url, { headers: headers, withCredentials: true }).retry(3);
superGetObs.subscribe(
(next) => { observer.onNext(next); },
(error) => { observer.onError(error); },
() => { observer.onCompleted(); }
);
} else {
observer.onError(new Error('Could not log you in automatically'));
}
}, (error) => { this._log.debug('resultObservable#then#error: ' + error); observer.onError(error); });
});
return resultObservable;
}
The full error stack: http://pastebin.com/ScrzsNh0
Make sure you import the retry-operator with import "rxjs/add/operator/retry";

Can not connect with API , so couldn't retrieve post from db?

I got problem while I move into https://github.com/DaftMonk/generator-angular-fullstack.
Before my project was working. Here is code for frontend and backend part related to comment.
I am getting all time error 404. I don't know why I cannot find following path.
POST http://localhost:9000/api/providers/554a1dba53d9ca8c2a2a31ff/posts/554b1726f1116e00256e3d82/comments 404 (Not Found)
I am struggling couple of days to discover which part of my code have problem but I couldn't realize that.
server side
in comment.controller
// Creates a new comment in the DB.
exports.create = function(req, res) {
console.log('i ma inside api');
Post.findById(req.originalUrl.split('/')[3], function (err, post) { //here can not find post at all.
if (err) {
return handleError(res, err);
}
if (!post) {
return res.status(404).send('Post not found');
}
Comment.create(req.body, function (err, comment) {
if (err) {
return handleError(res, err);
}
post.comments.push(comment.id);
post.save(function (err) {
if (err) return handleError(res, err);
return res.status(201).json(comment);
});
});
});
};
route.js
app.use('/api/providers/:providerId/posts/:postId/comments', require('./api/provider/post/comment'));
index.js
var controller = require('./comment.controller.js');
var router = express.Router();
router.get('/', controller.index);
router.get('/:id', controller.show);
router.post('/', controller.create);
router.put('/:id', controller.update);
router.patch('/:id', controller.update);
router.delete('/:id', controller.destroy);
router.put('/:id/upvote', controller.upvote);
in client side:
factory:
//create new comment for post
ob.createComment = function(providerId, postId,comment) {
console.log('i am inside factory');
return $http.post('/api/providers/'+ providerId + '/posts/' + postId + '/comments' ,comment, {
headers: {Authorization: 'Bearer '+Auth.getToken()}
}).success(function(data){
_.forEach(ob.provider.posts,function(value,index){
if(value._id === post._id){
ob.posts[index].comments.push(data);
}
})
ob.current.comments.push(data)
// ob.provider1._id.posts.push(data);
});
};
in my controller
$scope.addComment = function(){
// if(!$scope.title || $scope.title === '') { return; }
if(!$scope.body || $scope.body === '') { return; }
console.log('$stateParams',$stateParams);
providers.createComment($stateParams.providerId, $stateParams.postId,{
//title: $scope.title,
body: $scope.body
});
$scope.body = '';
$scope.title = '';
};
This is my model in whole the project.

Resources