I have a dynamic website. It uses mysql database which is provided by the hosting team. I need my android app to use the same database. How could I integrate the same.?
An Ajax request in Cordova/Phonegap is the same as using the standard jQuery:
For retrieving data I used in my app [minimalist code]:
$.getJSON(url).done(function (jsonData) {
console.debug('retrieved JSON');
// process your data here
}).fail(function () {
console.debug('cannot retrieve remote URL');
// error occurred
});
See also here: Calling a REST service from a Cordova application using jQuery and othere questions here in SO such as: How to call SOAP service from Phonegap (iPhone app).
Related
I'm new to using Svelte and would like to create a ordering website using Svelte. I know that I will need a database to keep track of the order, customer name, price etc. I have used MySQL before but I haven't learned how to connect a database to a website.
Is there a specific database that you can use if you are using Svelte?
Or is there a way to connect MySQL to Svelte?
I have searched about this on Youtube and Google but I'm not sure if it's different if you are using Svelte so I wanted to make sure.
Note: I have not started this project yet so I do not have any code to show I just want to know how you can connect a database if you're using Svelte.
Svelte is a front end javascript framework that run on the browser.
Traditionally, in order to use databases like mysql from a front end project such as svelte, (that contains only html,css and js), you would have to do it with a separate backend project. You can then communicate the svelte app and the backend project with the help of REST api. The same applies to other other front end libraries/frameworks like react, angular vue etc.
There are still so many ways to achieve the result. Since you are focusing on Svelte here are few things options
1 Sapper
Sapper is an application framework powered by svelte. You can also write backend code using express or polka so that you can connect to database of your choice (mysql / mongodb)
2 User Server less database
If you want you app simple and just focus on svelte app, you can use cloud based databases such as firebase. Svelte can directly talk to them via their javascript SDK.
3 monolithic architecture
To connect with mysql in the backend, you would need to use one serverside application programming language such as nodejs (express) php or python or whatever you are familiar with. Then use can embed svelte app or use api to pass data to the svelte app.
I can make an example with mongodb
You have to install the library
npm install mongodb
or add in package.json
Then you have to make a connection file that you have to call everytime you need to use the db
const mongo = require("mongodb");
let client = null;
let db = null;
export async function init() {
if(!client) {
client = await mongo.MongoClient.connect("mongodb://localhost");
db = client.db("name-of-your-db");
}
return { client, db }
}
for a complete example with insert you can see this video
https://www.youtube.com/watch?v=Mey2KZDog_A
You can use pouchdb, which gives you direct access to the indexedDB in the browser. No backend needed for this.
The client-pouchdb can then be replicated/synced with a remote couchdb. This can all be done inside you svelte-app from the client-side.
It is pretty easy to setup.
var db = new PouchDB('dbname');
db.put({
_id: 'dave#gmail.com',
name: 'David',
age: 69
});
db.changes().on('change', function() {
console.log('Ch-Ch-Changes');
});
db.replicate.to('http://example.com/mydb');
more on pouchdb.com
Also the client can save the data offline first and later connect to a remote database.
As i get question mostly about connection to backend, not a database. It is pity, but svelte app template has no way to connect backend "in box".
What about me, i'm using express middleware in front of rollup server. In this case you able to proxy some requests to backend server. Check code below
const proxy = require('express-http-proxy');
const app = require('express')();
app.use('/data/', proxy(
'http://backend/data',
{
proxyReqPathResolver: req => {
return '/data'+ req.url;
}
}
)
);
app.use('/', proxy('http://127.0.0.1:5000'));
app.listen(5001);
This script opend 5001 port where you have /data/ url proxied to backend server. And 5000 port still available from rollup server. So at http://localhost:5001/ you have svelte intance, connected to backend vi /data/ url, here you can send requests for fetching some data from database.
I build an api rest by express js simply to post an data in my server .
app.post("/register", function(request, response){
var username = request.body.username;
});
How i can do this with feathersjs ? and how i can call it from my reactjs app ?
Feathers is a drop-in replacement for Express. That means you can replace your const app = express(); with const app = feathers() and everything will work just the same, so what you are showing above you can also do with Feathers.
The real Feathers way to accomplish this however is through services which - with the other important concepts - are described in the basics guide.
There are pre-build services for several databases (which can be customized through hooks) but you can always create your own service. It is important to note that Feathers services - unlike the Express middleware you showed - will be available via HTTP (REST) and websockets (which also gets you real-time events). See here how service methods map to REST endpoints.
Your example in Feathers simply looks like this:
app.use('/register', {
create(data, params) {
// data is the request body e.g.
// data.username
// Always return a promise with the result data
return Promise.resolve(data);
}
});
I'm currently using the Async plugin to load Google Maps in our application using RequireJS (https://github.com/millermedeiros/requirejs-plugins):
define("googleMap", ['async!https://maps.googlee.com/maps/api/js?v=3&sensor=false']);
Then include it wherever I need it:
define(['googleMap'], function () { ... });
From China for example, Google Maps is forbidden and it will result with a "Load timeout for modules: async!googleMap". This will also break the entire website as the dependency is not available.
How can I catch that error so the app can run? Then wherever I use googleMap I would check that the object 'google' exists before using it.
I think you can ping the site before you pull your js, just like this answer does:
Is it possible to ping a server from Javascript?
I am creating a BlackBerry app that provides the functionalities of an already existing web application but making it suitable for mobile phone users. I am creating the mobile app using PhoneGap and leveraging BlackBerry WebWorks SDK. I need to send data to and receive data (submit forms, update profiles) from the mobile app to the server where the web application runs from. I also want users of the app to chat with other users of the mobile app through the BlackBerry Internet Service (BIS). I want the mobile app to be able to query the database already created for the existing web application so existing users who have downloaded the app can view their details on their BlackBerry device instead of their computers. Can someone please recommend a solution?
With phonegap you can send XMLHttpRequests via AJAX. You can do this in pure JavaScript or even easier with jQuery.
You'll need to do the database work with a server-side language, like php.
here's a simple example, assuming you have included jQuery in your Phonegap app.
window.onload = function (){
document.addEventListener("deviceready", deviceReady, false);
}
function deviceReady{
var userName = 'Hans';
var userShoeSize = 'Medium';
$.post("http://example.com/responseHandler.php", {
userName: userName, userShoeSize:userShoeSize},
function(data) {
alert(data.greeting+data.shoeSize);
}, "json");
}
and on the server in responseHandler.php:
<?php
header("Access-Control-Allow-Origin: *");
$response = array();
$response['greeting'] = 'Hi, '.$_POST['userName'];
$response['shoeSize'] = 'Your shoes are size '.$_POST['userShoeSize'];
echo json_encode($response);
?>
By echoing out a JSON encoded string on the server, javascript can easily parse the response. You don't have to use JSON, you can work with anything echoed out on the server.
Just remember to whitelist your page and allow querystrings from other origins on your server.
I'm new to this area and I'm developing a HTML5 mobile app that calls a restful webservices api and exchange JSON objects.
I want to authenticate the client once and give a a key/token that can be used afterwards until a pre-defined expiration date. I have 4 questions:
How can I secure the serverside webservices api? any tools whatsoever?
Can I use the local storage to store the key/token?
What are the phonegap security tools I can use for the client side?
How can I use OAUTH in this case?
How can I secure the serverside webservices api? any tools whatsoever?
OAuth may be overkill for your need, verify that you really need to use such a powerful (and complex) standard.
Two examples of PHP server side software that you may use:
Solberg-OAuth
SimpleSAMLphp
Can I use the local storage to store the key/token?
Yes! Be aware that you MUST use the OAuth 2.0 implicit grant flow in order to obtain the token at the client side.
What are the phonegap security tools I can use for the client side?
ChildBrowser is a plugin to open a separate browserwindow for the authentication process.
I've written a javascript library JSO that can do OAuth 2.0 for you. Other libraries exists as well.
https://github.com/andreassolberg/jso
How can I use OAUTH in this case?
Using JSO with Phonegap and ChildBrowser
Using JSO to perform OAuth 2.0 authorization in WebApps running on mobile devices in hybrid environment is an important deployment scenario for JSO.
Here is a detailed instruction on setting up JSO with Phonegap for iOS and configure OAuth 2.0 with Google. You may use it with Facebook or other OAuth providers as well.
Preparations
Install XCode from App Store, and iOS development kit
Install Phonegap 2.0, Cordova 2.0
Setup App
To create a new App
./create /Users/andreas/Sites/cordovatest no.erlang.test "CordovaJSOTest"
Install ChildBrowser
The original ChildBrowser plugin is available here.
https://github.com/purplecabbage/phonegap-plugins/tree/master/iPhone/ChildBrowser
However, it is not compatible with Cordova 2.0. Instead, you may use this fork of ChildBrowser which should be working with Cordova 2.0:
https://github.com/Shereef/ChildBrowserOnCordova200
What you need to do is to copy these files:
https://github.com/Shereef/ChildBrowserOnCordova200/tree/master/ChildBrowserOnCordova200/Plugins
in to your WebApp project area, by using drag and drop into the Plugins folder in XCode.
Now you need to edit the file found in Resources/Cordova.plist found in your WebApp project area.
In this file you need to add one array entry with '*' into ExternalHosts, and two entries into Plugins:
ChildBrowser -> ChildBrowser.js
ChildBrowserCommand -> ChildBrowserCommand
as seen on the screenshot.
(source: erlang.no)
Setting up your WebApp with ChildBrowser
I'd suggest to test and verify that you get ChildBrowser working before moving on to the OAuth stuff.
In your index.html file try this, and verify using the Simulator.
<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script>
<script type="text/javascript" charset="utf-8" src="ChildBrowser.js"></script>
<script type="text/javascript">
var deviceready = function() {
if(window.plugins.childBrowser == null) {
ChildBrowser.install();
}
window.plugins.childBrowser.showWebPage("http://google.com");
};
document.addEventListener('deviceready', this.deviceready, false);
</script>
Setting up JSO
Download the latest version of JSO:
https://github.com/andreassolberg/jso
The documentation on JSO is available there as well.
The callback URL needs to point somewhere, and one approach would be to put a callback HTML page somewhere, it does not really matter where, although a host you trust. And put a pretty blank page there:
<!doctype html>
<html>
<head>
<title>OAuth Callback endpoint</title>
<meta charset="utf-8" />
</head>
<body>
Processing OAuth response...
</body>
</html>
Now, setup your application index page. Here is a working example:
<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script>
<script type="text/javascript" charset="utf-8" src="ChildBrowser.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jquery.js"></script>
<script type="text/javascript" charset="utf-8" src="jso/jso.js"></script>
<script type="text/javascript">
var deviceready = function() {
var debug = true;
/*
* Setup and install the ChildBrowser plugin to Phongap/Cordova.
*/
if(window.plugins.childBrowser == null) {
ChildBrowser.install();
}
// Use ChildBrowser instead of redirecting the main page.
jso_registerRedirectHandler(window.plugins.childBrowser.showWebPage);
/*
* Register a handler on the childbrowser that detects redirects and
* lets JSO to detect incomming OAuth responses and deal with the content.
*/
window.plugins.childBrowser.onLocationChange = function(url){
url = decodeURIComponent(url);
console.log("Checking location: " + url);
jso_checkfortoken('facebook', url, function() {
console.log("Closing child browser, because a valid response was detected.");
window.plugins.childBrowser.close();
});
};
/*
* Configure the OAuth providers to use.
*/
jso_configure({
"facebook": {
client_id: "myclientid",
redirect_uri: "https://myhost.org/callback.html",
authorization: "https://www.facebook.com/dialog/oauth",
presenttoken: "qs"
}
}, {"debug": debug});
// For debugging purposes you can wipe existing cached tokens...
// jso_wipe();
// jso_dump displays a list of cached tokens using console.log if debugging is enabled.
jso_dump();
// Perform the protected OAuth calls.
$.oajax({
url: "https://graph.facebook.com/me/home",
jso_provider: "facebook",
jso_scopes: ["read_stream"],
jso_allowia: true,
dataType: 'json',
success: function(data) {
console.log("Response (facebook):");
console.log(data);
}
});
};
document.addEventListener('deviceready', this.deviceready, false);
</script>
How can I secure the serverside webservices api? any tools whatsoever?
Depends on which language the web service is written, php has zend framework for creating web services / nusoap etc. So all of the languages do provide info on how to secure the webservice.
Can I use the local storage to store the key/token?
Yes you can use local storage look at the phonegap documentation
What are the phonegap security tools I can use for the client side?
I dont think so there are any but you can search for some plugins or create your own plugin. Depends on what kind of security do you want to implement.
How can I use OAUTH in this case?
Here is a library for OAuth and this seems to be helpful. You can create a phone gap plugin to interact with the library or use a javascript oauth library(its with sample also).