React Native images save to php (laravel) server - php

I'm trying to save image to php application (made with laravel 6.0) using React Native. Here is my react native image picker
var ImagePicker = NativeModules.ImageCropPicker;
here is my image save function
addImages = async () => {
const { image, images } = this.state
const access_token = await AsyncStorage.getItem('access_token')
try {
let data = new FormData();
images.map((image, i) => {
data.append('id', id);
data.append('uri', image.uri);
data.append('type', image.mime);
data.append('name', 'test.jpg');
});
fetch(apiConfig.apiUrl + '/api/save-image', {
method: 'POST',
headers: {
'Content-Type' : 'multipart/form-data',
'Authorization': 'Bearer ' + access_token,
},
body:data
})
.then(function (response) {
return response.json();
})
.then(function (data) {
try {
console.log(data);
} catch (error) {
console.log(error);
}
}.bind(this))
.catch((error) => {
console.log(error)
});
}catch (error) {
console.log(error)
}
}
Here is my php code
public function saveImage(Request $request)
{
header( "Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Origin: *");
try {
$file= array('file'=>$request->uri);
Storage::disk('public')->put($request->imgName,File::get($file->file));
return response()->json(['true'=>'Successfully Created'], 200);
} catch (\Exception $e) {
Log::info('vehicle image: ', [$e->getMessage()]);
return response()->json(['error'=>$e], 200);
}
}
When I try to save I'm getting SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data.
when I return the $request->uri I'm getting something like this file:///data/user/0/com.carup/cache/react-native-image-crop-picker/IMG_20191103_161929.jpg
How can I fix this?
How can I fix this?

You need to specify file name as the third parameter to data.append:
data.append('file', image.uri, 'test.jpg');

Finally I have fixed it with Base64 method. Here is my code.
pick images with base64
pickMultipleBase64=()=> {
ImagePicker.openPicker({
multiple: true,
width: 300,
height: 300,
includeBase64: true,
includeExif: true,
}).then(images => {
this.setState({
images: images.map(image => {
return {uri: `data:${image.mime};base64,`+ image.data, width: image.width, height: image.height,type:image.mime}
}),
});
}).catch(e => alert(e));
}
And uploaded with other details like this
addImages = async () => {
const { image, images, stockNo } = this.state
const access_token = await AsyncStorage.getItem('access_token')
if(access_token == null) {
return(
this.gotoLogin()
)
}
this.setState({
isLoading:true,
message:'',
status:true
})
try {
let data = new FormData();
images.map((image, i) => {
data.append('id', id);
data.append('stock', stockNo);
data.append('chassis', chassis_no);
data.append('file'+i, this.state.images[i].uri);
data.append('type'+i, this.state.images[i].type);
imageCount++
});
data.append('imageCount', imageCount);
// console.log(data);
fetch(apiConfig.apiUrl + '/api/save-image', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + access_token,
},
body:data
})
.then(function (response) {
return response.json();
})
.then(function (data) {
console.log(data);
imageCount = 0
try {
this.setState({
isLoading: false,
message:data.true ? data.true:data.error,
messageColor:data.true ? CarColors.success : CarColors.error,
btnStatus:true
// chassis:''
})
if(data.true){
this.setState({
image:null,
images: null,
})
}
} catch (error) {
this.removeToken();
console.log('1 '+error);
}
}.bind(this))
.catch((error) => {
this.setState({
isLoading: false,
message:'error',
messageColor:CarColors.error,
})
console.log(error)
});
}catch (error) {
console.log(error)
}
And my php(laravel) code is like this. Here I have created a new folder (with vehicle id) in storage and save images to separate folders.
public static function saveImage($request)
{
$dir = "./storage/vehicle/" . $request->id;
if (is_dir($dir) === false) {
mkdir($dir);
}
DB::beginTransaction();
try {
for ($i = 0; $i < $request->imageCount; $i++) {
$type = [];
$file = 'file' . $i;
$mime = 'type' . $i;
$data = $request->$file;
$type = explode('/', $request->$mime);
$extension = $type[1];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$Imgdata =Images::create([
'vehicle_id' => $request->id,
'img_name' => $i.'.'.$extension,
'img_ext' => $extension,
'img_order' => '0',
]);
Storage::disk('vehicle')->put($request->id . '/' . $i . '.' . $extension, $data);
}
//Update Vehicle table ImageStatus
$Vehicle = Vehicle::where('id',$request->id)->update([
'img_status' => '1',
]);
return response()->json(['true' => 'Successfully Uploaded'], 200);
} catch (\Exception $e) {
DB::rollback();
Log::info('vehicle image name save issue: ', [$e->getMessage()]);
return 'false';
}
}
Hope this will help others who are going to upload multiple images with react native

Related

how can i upload image using react native expo image to my local server PHP / Database MySQL

I'm making a mobile application using expo client to allow user to upload image or take from a camera and then the image saves on my local server on PHP / Database MySQL. How do I do that thing if I'm using an expo?
for example code in react native (saving to PHP local server but not save database)
import React, { Component } from 'react';
import {
ActivityIndicator,
Button,
Clipboard,
Image,
Share,
StatusBar,
StyleSheet,
Text,
TouchableOpacity,
View,
} from 'react-native';
import { Constants } from 'expo';
import * as ImagePicker from 'expo-image-picker';
import * as Permissions from 'expo-permissions';
export default class App extends Component {
state = {
image: null,
uploading: false,
};
render() {
let {
image
} = this.state;
return (
<View style={styles.container}>
<StatusBar barStyle="default" />
<Text
style={styles.exampleText}>
Example: Upload ImagePicker result
</Text>
<Button
onPress={this._pickImage}
title="Pick an image from gallery"
/>
<Button onPress={this._takePhoto} title="Take a photo" />
{this._maybeRenderImage()}
{this._maybeRenderUploadingOverlay()}
</View>
);
}
_maybeRenderUploadingOverlay = () => {
if (this.state.uploading) {
return (
<View
style={[StyleSheet.absoluteFill, styles.maybeRenderUploading]}>
<ActivityIndicator color="#fff" size="large" />
</View>
);
}
};
_maybeRenderImage = () => {
let {
image
} = this.state;
if (!image) {
return;
}
return (
<View
style={styles.maybeRenderContainer}>
<View
style={styles.maybeRenderImageContainer}>
<Image source={{ uri: image }} style={styles.maybeRenderImage} />
</View>
<Text
onPress={this._copyToClipboard}
onLongPress={this._share}
style={styles.maybeRenderImageText}>
{image}
</Text>
</View>
);
};
_share = () => {
Share.share({
message: this.state.image,
title: 'Check out this photo',
url: this.state.image,
});
};
_copyToClipboard = () => {
Clipboard.setString(this.state.image);
alert('Copied image URL to clipboard');
};
_takePhoto = async () => {
const {
status: cameraPerm
} = await Permissions.askAsync(Permissions.CAMERA);
const {
status: cameraRollPerm
} = await Permissions.askAsync(Permissions.CAMERA_ROLL);
// only if user allows permission to camera AND camera roll
if (cameraPerm === 'granted' && cameraRollPerm === 'granted') {
let pickerResult = await ImagePicker.launchCameraAsync({
allowsEditing: true,
aspect: [4, 3],
});
this._handleImagePicked(pickerResult);
}
};
_pickImage = async () => {
const {
status: cameraRollPerm
} = await Permissions.askAsync(Permissions.CAMERA_ROLL);
// only if user allows permission to camera roll
if (cameraRollPerm === 'granted') {
let pickerResult = await ImagePicker.launchImageLibraryAsync({
allowsEditing: true,
aspect: [4, 3],
});
this._handleImagePicked(pickerResult);
}
};
_handleImagePicked = async pickerResult => {
let uploadResponse, uploadResult;
try {
this.setState({
uploading: true
});
if (!pickerResult.cancelled) {
uploadResponse = await uploadImageAsync(pickerResult.uri);
uploadResult = await uploadResponse.json();
this.setState({
image: uploadResult.location
});
}
} catch (e) {
console.log({ uploadResponse });
console.log({ uploadResult });
console.log({ e });
alert('Upload failed, sorry :(');
} finally {
this.setState({
uploading: false
});
}
};
}
async function uploadImageAsync(uri) {
let apiUrl = 'http://192.168.0.18/upload-api/uploading.php';
let uriParts = uri.split('.');
let fileType = uriParts[uriParts.length - 1];
let formData = new FormData();
formData.append('fileToUpload', {
uri,
name: `fileToUpload.${fileType}`,
type: `image/${fileType}`,
});
let options = {
method: 'POST',
body: formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
};
return fetch(apiUrl, options);
}
and here is my PHP
<?php
$target_dir = 'uploads/';
$target_file = $target_dir . basename($_FILES['fileToUpload']['name']);
$status = array();
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file)) {
$status['status']=1;
$status['description']='upload success';
} else {
$status['status']=0;
$status['description']='upload failed';
}
echo json_encode($status);
?>
Any solution to this? thank you
You can use Fetch Api to upload image
var photo = {
uri: selectImg.localUri,
type: 'image/jpeg',
name: 'photo.jpg',
};
var form = new FormData();
form.append("ProfilePicture", photo);
fetch(
Constants.API_USER + 'me/profilePicture',
{
body: form,
method: "PUT",
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ' + user.token
}
}
).then((response) => response.json())
.catch((error) => {
alert("ERROR " + error)
})
.then((responseData) => {
alert("Succes "+ responseData)
}).done();

push notifications do NOT shown to the subscribers (web-push-php)

I'm using web-push-php library for my project. The user can register/un-register for web notification but the message does NOT push to the specific user. following are my codes
main.js
'use strict';
const applicationServerPublicKey = ew.vars.PubKey;
const pushButton = document.querySelector('.pushBTN');
let isSubscribed = false;
let swRegistration = null;
function urlB64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
//CODE HERE
//1
if ('serviceWorker' in navigator && 'PushManager' in window) {
console.log('Service Worker and Push is supported');
navigator.serviceWorker.register('sw.js')
.then(function(swReg) {
console.log('Service Worker is registered', swReg);
swRegistration = swReg;
})
.catch(function(error) {
console.error('Service Worker Error', error);
});
} else {
console.warn('Push messaging is not supported');
pushButton.textContent = 'Push Not Supported';
}
//2
function initializeUI() {
pushButton.addEventListener('click', function() {
pushButton.disabled = true;
if (isSubscribed) {
unsubscribeUser();
} else {
subscribeUser();
}
});
// Set the initial subscription value
swRegistration.pushManager.getSubscription()
.then(function(subscription) {
isSubscribed = !(subscription === null);
updateSubscriptionOnServer(subscription);
if (isSubscribed) {
console.log('User IS subscribed.');
} else {
console.log('User is NOT subscribed.');
}
updateBtn();
});
}
//3
function updateBtn() {
if (Notification.permission === 'denied') {
pushButton.textContent = 'Push Messaging Blocked.';
pushButton.disabled = true;
updateSubscriptionOnServer(null);
return;
}
if (isSubscribed) {
pushButton.innerHTML = '<i class="fas fa-bell-slash text-danger"></i>';
} else {
pushButton.innerHTML = '<i class="fas fa-bell text-success"></i>';
}
pushButton.disabled = false;
}
//4
navigator.serviceWorker.register('sw.js')
.then(function(swReg) {
console.log('Service Worker is registered', swReg);
swRegistration = swReg;
initializeUI();
})
//5
function subscribeUser() {
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey
})
.then(function(subscription) {
console.log('User is subscribed.');
updateSubscriptionOnServer(subscription);
isSubscribed = true;
updateBtn();
})
.catch(function(err) {
console.log('Failed to subscribe the user: ', err);
updateBtn();
});
}
//6
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey
})
//7
swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey
})
.then(function(subscription) {
console.log('User is subscribed.');
updateSubscriptionOnServer(subscription);
isSubscribed = true;
updateBtn();
})
.catch(function(err) {
console.log('Failed to subscribe the user: ', err);
updateBtn();
});
//8
function updateSubscriptionOnServer(subscription) {
// TODO: Send subscription to application server
if (subscription) {
const key = subscription.getKey('p256dh');
const token = subscription.getKey('auth');
fetch('webpushregister.php', {
method: 'post',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify({
endpoint: subscription.endpoint,
key: key ? btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('p256dh')))) : null,
token: token ? btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('auth')))) : null,
axn: 'subscribe'
})
}).then(function(response) {
return response.text();
}).then(function(response) {
console.log(response);
}).catch(function(err) {
// Error :(
console.log('error');
});
} else {
//subscriptionDetails.classList.add('is-invisible');
}
}
//9
function unsubscribeUser() {
swRegistration.pushManager.getSubscription()
.then(function(subscription) {
if (subscription) {
//updating database
const key = subscription.getKey('p256dh');
const token = subscription.getKey('auth');
fetch('webpushregister.php', {
method: 'post',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify({
endpoint: subscription.endpoint,
key: key ? btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('p256dh')))) : null,
token: token ? btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('auth')))) : null,
axn: 'unsubscribe'
})
}).then(function(response) {
return response.text();
}).then(function(response) {
console.log(response);
}).catch(function(err) {
// Error :(
console.log('error removing from db');
throw new error('error removing from db');
});
//end updating database
return subscription.unsubscribe();
}
})
.catch(function(error) {
console.log('Error unsubscribing', error);
})
.then(function() {
updateSubscriptionOnServer(null);
console.log('User is unsubscribed.');
isSubscribed = false;
updateBtn();
});
}
//10
swRegistration.pushManager.getSubscription()
.then(function(subscription) {
if (subscription) {
// TODO: Tell application server to delete subscription
return subscription.unsubscribe();
}
})
.catch(function(error) {
console.log('Error unsubscribing', error);
})
my sw.js
'use strict';
//1
self.addEventListener('push', function(event) {
console.log('[Service Worker] Push Received.');
console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);
const title = 'Push Codelab';
const options = {
body: 'Yay it works.4444444444',
icon: 'images/icon.png',
badge: 'images/badge.png'
};
const notificationPromise = self.registration.showNotification(title, options);
event.waitUntil(notificationPromise);
});
//2
self.addEventListener('notificationclick', function(event) {
console.log('[Service Worker] Notification click Received.');
event.notification.close();
event.waitUntil(
clients.openWindow('https://developers.google.com/web/')
);
});
//installing web application
self.addEventListener("install", function(event) {
event.waitUntil(preLoad());
});
var preLoad = function(){
console.log("Installing web app");
return caches.open("offline").then(function(cache) {
console.log("caching index and important routes");
return cache.addAll(["/", "/offline.html"]);
});
};
self.addEventListener("fetch", function(event) {
event.respondWith(checkResponse(event.request).catch(function() {
return returnFromCache(event.request);
}));
event.waitUntil(addToCache(event.request));
});
var checkResponse = function(request){
return new Promise(function(fulfill, reject) {
fetch(request).then(function(response){
if(response.status !== 404) {
fulfill(response);
} else {
reject();
}
}, reject);
});
};
var addToCache = function(request){
return caches.open("offline").then(function (cache) {
return fetch(request).then(function (response) {
console.log(response.url + " was cached");
return cache.put(request, response);
});
});
};
var returnFromCache = function(request){
return caches.open("offline").then(function (cache) {
return cache.match(request).then(function (matching) {
if(!matching || matching.status == 404) {
return cache.match("offline.html");
} else {
return matching;
}
});
});
};
and my php file
<?php
$siteconf = new SiteConfig();
use Minishlink\WebPush\WebPush;
use Minishlink\WebPush\Subscription;
$subscriber = ExecuteRow("SELECT * FROM subscribers ORDER BY id DESC LIMIT 1");
$auth = array(
'VAPID' => array(
'subject' => 'https://github.com/Minishlink/web-push-php-example/',
'publicKey' => $siteconf->PublicKey, // don't forget that your public key also lives in app.js
'privateKey' => $siteconf->PrivateKey, // in the real world, this would be in a secret file
),
);
// array of notifications
$notifications = [
[
'subscription' => Subscription::create([
'endpoint' => $subscriber['endpoint'],
'publicKey' => $siteconf->PublicKey,
'authToken' => $subscriber['auth'],
]),
'payload' => 'hello !',
],
];
$webPush = new WebPush($auth);
// send multiple notifications with payload
foreach ($notifications as $notification) {
$webPush->sendNotification(
$notification['subscription'],
$notification['payload'] // optional (defaults null)
);
}
/**
* Check sent results
* #var MessageSentReport $report
*/
foreach ($webPush->flush() as $report) {
$endpoint = $report->getRequest()->getUri()->__toString();
if ($report->isSuccess()) {
echo "[v] Message sent successfully for subscription {$endpoint}.";
} else {
echo "[x] Message failed to sent for subscription {$endpoint}: {$report->getReason()}";
}
}
/**
* send one notification and flush directly
* #var \Generator<MessageSentReport> $sent
*/
$sent = $webPush->sendNotification(
$notifications[0]['subscription'],
$notifications[0]['payload'], // optional (defaults null)
true // optional (defaults false)
);
?>
I'm trying to send message to the last user in our database. I receive success message but the push message does NOT deliver.
What's the reason? how to fix it?
You are missing the following:
'contentEncoding' => $message["contentEncoding"]
It should be placed under the comment // array of notifications.
I am having an issue regarding this but it's the opposite of yours. I am only able to send a notification for the very last row but not the other rows.

docx file download system using laravel - vuejs

I want to send a docx file to the client in the response of a get request:
Here's the Laravel controller code:
public function file($id)
{
$dlink = resource_path('temp/' . $id . '.docx');
$headers = [
'Content-Type' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
];
return response()->download($dlink, $id . '.docx', $headers);
}
VueJS code:
axios.get(`${location.protocol}//${location.host}/api/download/${response.data}`,
{ responseType: "arraybuffer" }
)
.then(response => {
this.downloadFile(response);
})
.catch(err => alert(err));
downloadFile(response) {
var newBlob = new Blob([response.body], {
type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
});
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(newBlob);
return;
}
const data = window.URL.createObjectURL(newBlob);
var link = document.createElement("a");
link.href = data;
link.download = "resume.docx";
link.click();
setTimeout(function() {
window.URL.revokeObjectURL(data);
}, 100);
}
It doesn't show any error. but downloads a corrupted 9bytes docx file.
changing response.body to response.data did the job.

cakephp 3 + Jwt + angular - 401 (Unauthorized)

well I need send username and password for generate the token for a login, the problem always that I send from the client (angular) response with error, but when I send it from postman work fine.
In cakephp 3.
public function initialize()
{
parent::initialize();
$this->Auth->allow(['add', 'token', 'me']);
}
public function token()
{
$user = $this->Auth->identify();
if (!$user)
{
throw new UnauthorizedException('Invalid username or password');
}
$this->set([
'success' => true,
'data' => [
'user_id' => $user['id'],
'token' => JWT::encode([
'sub' => $user['id'],
'exp' => time() + 604800
],
Security::salt())
],
'_serialize' => ['success', 'data']
]);
}
in angular how I send it
$scope.doLogin = function()
{
dataLogin = {
username: vm.username,
password: vm.password
};
console.log(dataLogin);
// call the Auth.login() function
//$scope.processing = true;
$scope.error = '';
Auth.login(dataLogin)
.then(function(data) {
if (data.success)
$state('home');
else
console.log(data);
$scope.error = data.message;
});
};
and
authFactory.login = function(dataLogin) {
return apiService.request('POST', '/api/users/token', dataLogin).then(function(data) {
AuthToken.setToken(data.token);
return data;
});
};
apiService for app angular
(function(){
angular
.module('appDekma')
.factory('apiService', apiService);
apiService.$inject = ['$http'];
function apiService($http) {
return {
request: sendRequest
};
function sendRequest(method, endpoint, data) {
var API_HOST = 'http://localhost/dekma_backend';
var req = {
method: method || 'GET',
url: API_HOST + endpoint,
data: data || '',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Headers': 'Accept, Authorization, Cache-Control, Content-Type, X-Requested-With, x-csrf-token',
'Access-Control-Max-Age': '3600'
}
};
return $http(req)
.then(successCallback, errorCallback);
function successCallback(response)
{
return response.data;
}
function errorCallback(error) {
var message = 'Something terrible happened!';
if (error.data && error.data.code)
{
switch (error.data.code)
{
case 500:
break;
case 401:
break;
case 403:
break;
case 404:
message = 'Could not find content';
break;
default:
break;
}
}
return error.data;
}
}
}
})();
angular.module('app').config(['$routeProvider', '$httpProvider', function ($routeProvider, $httpProvider, urls) {
$httpProvider.interceptors.push(['$q', '$location', '$localStorage', function ($q, $location, $localStorage) {
return {
'request': function (config) {
config.headers = config.headers || {};
if ($localStorage.token) {
config.headers.Authorization = 'Bearer ' + $localStorage.token;// JWT token stored in localstorage
config.headers.Accept = 'application/json';
}
return config;
},
'responseError': function (response) {
console.log(response);
if (response.status === 401 || response.status === 403 || response.status === 500) {
var login_url = urls.BASE+'users/login';
}
return $q.reject(response);
}
};
}]);
$routeProvider
.when('/', {
templateUrl: "public/html/" + 'your_html_page.html',
controller: 'your_anuglar_controller'
})
.otherwise({ redirectTo: '/' });
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

Login with Nativescript and Prestashop

I have a shop APP with Prestashop connection and developed in Android Studio, but I need to make an hybrid APP, in this case with Nativescript. To create the layouts and style is all great but I don't know How to make a connection with webservices.
In my first APP to Post the values I have:
new AuthentificationTask().execute(Config.LOGIN_URL + "&email=" + Login.getText().toString() + "&passwd=" + PassWord.getText().toString());
And in the PHP:
if(Tools::getValue("boutique") && Tools::getValue("email") && Tools::getValue("passwd"))
{
Shop::setIdShop(Tools::getValue('boutique'));
$cntxt = Context::getContext();
$cntxt->shop = new Shop(Tools::getValue('boutique'));
if(Tools::getValue("email"))
{
if (!Validate::isEmail(Tools::getValue("email")))
echo json_encode(array('valide' => 0));
$customer = New Customer();
//$customerExists = Customer::customerExists(Tools::getValue("email") , true);
$customer = $customer->getByEmail(Tools::getValue("email") ,Tools::getValue("passwd"));
if (#$customer->active) {
echo json_encode(array('valide' => 1,'id' => $customer->id));
}else{
echo json_encode(array('valide' => 0));
}
}else{
echo json_encode(array('valide' => 0));
}
}
It's all OK, I get the value valide (1,0).
Now with Nativescript, I don't know, How I can pass the values, I write this code:
viewModel.login = function() {
return fetchModule.fetch(config.url, {
method: "POST",
body: JSON.stringify({
boutique: 18,
email: viewModel.get("email") ,
passwd: viewModel.get("passwd"),
}),
headers: {
"Content-Type": "application/json"
}
})
.then(handleErrors)
.then(function(response) {
console.log('NO');
return response.json();
})
.then(r => { return r.json(); }).then(function (r) {
//var Valide = ResponceObject.getInt("valide") ;
console.log('SI'+result);
config.token = data.Result.access_token;
});
};
I really need your help.

Categories