Problem server request with genymotion emulator - ajax

I am developing a cross-platform application with phonegap framework. I tried most of the command for contacting the server into the browser (phonegap run browser) and they worked fine. Then i tried to lunch the application in the genymotion emulator (phonegap run android) but it seem that the call to the server (made with ajax) always end in error but it is the same code that worked on the browser
//LOGIN
function fLogin(){
$("#bacheca").hide();
console.log("prova jquery");
$("#log").click(function(){
let nome = $("#username").val();
let pass = $("#password").val();
console.log("Clicked login with values: "+nome+" "+pass);
$.ajax({
method: "post",
url: "..myserver..",
data: {username: nome, password: pass},
success: function(result){
console.log("found: "+result);
sessione = result;
showHome();
localStorage.setItem("sessione",sessione);
localStorage.setItem("myname",nome);
myname = localStorage.getItem("myname");
},
error: function(){
console.log("error");
}
});
})
}

Obviously you dont have internet access?
Add the whitelist plugin
<gap:plugin name="cordova-plugin-whitelist" source="npm" />
You might need to add this meta tag on the head
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src * 'unsafe-inline'; script-src * 'unsafe-inline'; media-src *">
And add this two lines to the config.xml
<allow-navigation href="http://*/*" />
<allow-intent href="https://*/*" />

Related

react-native-image-picker upload image fetch network error

I use react-native-image-picker to upload image to a server. I use the following code:
sendPhoto = async () =>{
const fileToUpload = {
type:'image/jpg',
uri: 'file://'+this.state.photo.path,
name:'uploadimage.jpg'
}
console.log(fileToUpload);
let data = new FormData();
data.append('file_attachment', { type:'image/jpg', uri: this.state.photo.path, name:'uploadimage.jpg'})
fetch (settings.ajaxurl+'sickFishUpload',{
method: 'POST',
body: data,
headers: {
'Content-Type': 'multipart/form-data; ',
},
})
.then( (response) => response.json())
.then((res) => {
console.log(res);
//console.log(res);
})
.catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
// ADD THIS THROW error
throw error;
})
}
Unfortunatelly It cannot communicate with the server. I got this message: There has been a problem with your fetch operation: TypeError: Network request failed.
If I erase this json from the data:
{ type:'image/jpg', uri: this.state.photo.path, name:'uploadimage.jpg'}
it can communicate with the server.
I set the AndroidManifest.xml with
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
and the application tag with
android:requestLegacyExternalStorage="true"
I'm totally stucked. Do you have any idea what is wrong? Of course I 've found this question in a previous post, but It is more than a years old and my solution is worked with the previous version of react-native. So I don't know how to upgrade my code...
Every suggestion is very welcome.
thx
Adam

Nativescript ssl pining issue

I have to enable ssl pining in my app. So, I had to use https://github.com/gethuman/nativescript-https plugin.
I have follow the implementation steps correctly. But when I make the https request, iOS app crash in AFNetworking EXC_BAD_Access error
Android app gives this error
JS: nativescript-https > Disabled SSL pinning by default
JS: nativescript-https > enableSSLPinning error ReferenceError: okhttp3 is not defined
JS: Https.request error ReferenceError: okhttp3 is not defined
Certs folder
reference.d.ts
/// <reference path="./node_modules/tns-core-modules/tns-core-modules.d.ts" />
/// <reference path="./node_modules/tns-platform-declarations/android.d.ts" />
/// <reference path="./node_modules/tns-platform-declarations/ios.d.ts" />
imports
import { File, Folder, knownFolders, path } from 'file-system'
import * as Https from 'nativescript-https'
in the constructor
let dir = knownFolders.currentApp().getFolder('certs')
let certificate = dir.getFile('httpbin.org.cer').path
Https.enableSSLPinning({ host: 'httpbin.org', certificate: certificate});
method
clickLogin(){
Https.request({
url: 'https://httpbin.org/get',
method: 'GET',
headers: {
'content-type': 'application/json'
},
}).then(function(response) {
console.log('Https.request response', response)
}).catch(function(error) {
console.error('Https.request error', error)
})
}
Please help me to identify whats is the issue here.
tns version 4.0.1
node v6.11.5
Android: Remove and re-add android platform. Clean build resolve the issue
iOS : Downgrade to Afnetworking 3.1.0 resolve the issue

API Call From Word Web Add-In (Office.Js) Is Not Working: CORS Issue?

Friends,
I am trying to call API from Word Add-in and getting "Access Denied" error. I did some research and it looks like "Cross Origin Resource Sharing" is the cause.
1. Web API
I am hosting Web API 2 locally at "http://localhost:61546/api/ORG_NAMES"
& I have enabled CORS to accept all origins, See below WebApiConfig.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
2. Test Application
To test this API to ensure it supports CORS, I have created below page and hosted on localhost:52799/home.html, I was able to get expected response. I have tested this in IE 10 & Chrome.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function () {
var obj;
.support.cors = true;
$.getJSON("http://localhost:61546/api/ORG_NAMES/112233",
function (data) {
alert(data.ORG_ID);
});
});
});
</script>
</head>
<body>
<button>Click me</button>
</body>
3. Word Add-In
Now I wanted to call this API from my Word Web Add-In. Word Add-In running from different host https://localhost:44339/, see below code. Here getJSON returns "Access Denied".
var OrgID;
$.getJSON("http://localhost:61546/api/ORG_NAMES/112233",
function (data) {
OrgID = data.ORG_ID;
});
Also when I call API from word add-in, it's not going to fiddler.
Note: This is "Web Add-ins --> Word Add-in" project.
4. Fix - Need Help
Not sure why I am getting "Access Denied" error from Word-Add-In, if CORS is the issue then my test application (#2) shouldn't have worked, correct ?
I have tried call JSON using "$.ajax", "XMLHttpRequest" but it didn't work.I might be missing some configuration settings.
Appreciate any help here.
Let me know if you need more information.
Since it sounds like an issue within an Office Add-in only, rather than in a regular page, have you tried setting your AppDomains in the manifest file? See "Specify domains you want to open in the add-in window" in https://dev.office.com/docs/add-ins/overview/add-in-manifests
<?xml version="1.0" encoding="UTF-8"?>
<OfficeApp xmlns="http://schemas.microsoft.com/office/appforoffice/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="TaskPaneApp">
<Id>c6890c26-5bbb-40ed-a321-37f07909a2f0</Id>
<Version>1.0</Version>
<ProviderName>Contoso, Ltd</ProviderName>
<DefaultLocale>en-US</DefaultLocale>
<DisplayName DefaultValue="Northwind Traders Excel" />
<Description DefaultValue="Search Northwind Traders data from Excel"/>
<AppDomains>
<AppDomain>https://www.northwindtraders.com</AppDomain>
</AppDomains>
<DefaultSettings>
<SourceLocation DefaultValue="https://www.contoso.com/search_app/Default.aspx" />
</DefaultSettings>
<Permissions>ReadWriteDocument</Permissions>
</OfficeApp>
You will not need Jsonp if you are making Ajax calls. You will have to make sure that you all launches with HTTPS, if it is launching in HTTP it will block that traffic. Remember that office-js back bone is IE and there for; for security purposes the api will only allow HTTPS
Update
Remember that an office-js add in is actually two projects and you must make sure your projects are both launching in HTTPS. Also I would just look over the Manifest file and look at your source and make sure that is point at HTTPS
I had same issue using ajax could not call web-api.NET MVC.
Web api side(Server side):
Implement CORS in Web api because excel office.js works on diffent port and binds proxy object of server inside excel while web api are held on another port so it is as good as having 2 different domains on local so browser automatically blocks request made.
So Cross origin Resource sharing is required.
Enable Https for web apis.
http://csharp-video-tutorials.blogspot.com/2016/09/aspnet-web-api-enable-https.html
Client side
Just make call using ajax as shown below.
url: 'https://localhost:44319/api/Default/PostItems'
Note : https : is compulsory required .
function makeAjaxCall(rangeJSON) {
$.ajax({
url: 'https://localhost:44319/api/Default/PostItems',
type: 'POST',
data: rangeJSON,
contentType: 'application/json;charset=utf-8',
}).done(function (data) {
console.log(data)
app.showNotification(data.Status, data.Message);
}).fail(function (status) {
app.showNotification('Error', 'Could not communicate with the server.');
}).always(showResponse);
}
function exceltojson() {
Excel.run(function (ctx) {
var range = ctx.workbook.worksheets.getItem("Sheet1").getRange("A1:BO765");
range.load("values, numberFormat");
ctx.sync().then(
function () {
makeAjaxCall(JSON.stringify(range.values));
}).catch(function (error) {
console.log(error);
});
});
function showResponse(object) {
console.log(object);
$("#output").text(JSON.stringify(object,null, 4));
}

SIGNALR: $.connection.hub.start() results in "Error parsing negotiate response."

I had basic SignalR functionality implemented and working in my MVC5/AngularJS application recently, but after shelfing and unshelfing the changes I am now getting an error when the connection is negotiated in $.connection.hub.start().
I've stripped down the code to the very basics, but still get this error. Poking around in the jquery.signalR-2.2.0.js where the negotiate request is made, I found that the result returned from the ajax request to http://localhost:44379/signalr/negotiate?clientProtocol=1.5&connectionData=[] is returning the HTML of the page instead of JSON data!
connection._.negotiateRequest = /* This is on line 659 */ signalR.transports._logic.ajax(connection, {
url: url, // http://localhost:44379/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%5D
error: function (error, statusText) {
// Irrelevant code removed.
},
success: function (result) { // We get here at least...
var res,
keepAliveData,
protocolError,
transports = [],
supportedTransports = [];
try {
res = connection._parseResponse(result); // This fails because result contains HTML.
} catch (error) {
// error.message is "Unexpected token <"
onFailed(signalR._.error(resources.errorParsingNegotiateResponse, error), connection);
return;
}
Here is my javascript for establishing the hub/connection:
$(function () {
var hub = $.connection.testHub;
if (hub)
console.log("SignalR hub initialized.");
$.connection.hub.start().done(function () {
console.log("SignalR connection established.");
}).fail(function (err) {
console.log("Error starting SignalR connection: " + err); // Ends up here.
});
});
And the script references (I have the signalr code in a separate js file named messaging.js):
<script src="~/assets/js/signalr/jquery.signalR-2.2.0.js"></script>
<script src="~/Scripts/messaging/messaging.js"></script>
<script src="~/signalr/hubs"></script>
I don't really understand why the ajax response from signalr/negotiate would be returning HTML instead of JSON. I've stripped down the server side hub code to an empty class with [AllowAnonymous] to ensure nothing in there was causing the problem. I have the app.MapSignalR() call in Startup.cs in place. My first thought, since this occurred after shelfing and unshelfing, was that something didn't make it into the shelf and was lost, but I can't seem to find anything missing...
Anyone have any ideas?
I found the problem while playing with the rules in web.config.
Previously, I had this rule for signalr:
<add input="{REQUEST_URI}" matchType="Pattern" pattern="/signalr/hubs" negate="true" />
Changing the pattern allowed communication with /signalr/negotiate, I think:
<add input="{REQUEST_URI}" matchType="Pattern" pattern="^/(signalr)" negate="true"/>
...I have no idea how this worked before.

React-Router throws Invariant Violation on setState() in ajax call

I'm trying to find a tricky error that I'm experiencing with react-router. For some reason, setting the state of one of my child components in a top-level page route causes the following error:
Uncaught Error: Invariant Violation: Missing "userId" parameter for path "/user/:userId"
This error happens regardless of whether or not I am navigating to that path. My routes look this:
var routes = (
<Routes>
<DefaultRoute handler={LoginPage} />
<Route name="login" handler={LoginPage} />
<Route name="home" handler={HomePage} />
<Route name="category" path="/category/:category" handler={CategoriesPage}/>
<Route name="profile" path="/user/:userId" handler={ProfilePage}/>
</Routes>
);
And my ajax call looks like this:
var Feed = React.createClass({
getInitialState: function() {
return { feedItems: [] };
},
componentDidMount: function() {
$.ajax({
url: '/api/transactions',
dataType: 'json',
success: function(transactions) {
this.setState({ feedItems: transactions });
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
....
This Feed is generated on a bunch of pages, including the HomePage and the ProfilePage. I'm having a lot of trouble figuring out how the :userId parameter could be related to the Ajax call in the feed, but that's where the stack trace leads me. Any help with what is going on here would be much appreciated.
UPDATE: Found the problem. My mongo database was out of date (model schemas changed), which was causing a host of problems, bubbling up to this Invariant Violation. I'm still not entirely sure how the two were related, but deleting old objects fixed the problem.
Thanks, #ritmatter for solving this yourself !
Just as a reference, here the answer with a link to the docs.
Remember in all your react-router <Link> elements you have in your code, to include the params object for links pointing to a parameterized route:
<Link to="BillingInfo" params={userId:"user876718236"}>Your Billing Information</Link>
<!-- linking to /user876718236/billing-info -->
Have a look here for details: react-router/Link
UPDATE [2015-03-29] corrected JSX param braces. Thanks to #Akay.
UPDATE: v1.0 (November 2015)
Named paths are no longer supported, you link to full paths. String templates in ES6 are handy for this:
// v0.13.x
<Link to="user" params={{userId: user.id}}>Mateusz</Link>
// v1.0
<Link to={`/users/${user.id}`}>Mateusz</Link>
From Changelog: Links.

Resources