Issues with Cordova file transfer not connecting to server endpoint

I've been attempting to utilize FT (cordova file-transfer) to create a file and send it to my express app. However, I've encountered an issue where express does not receive the request. Previously, it was functioning correctly, but now it has stopped, and I am working to determine the cause.

Below is a snippet of my code:

Initially, I capture a photo using the cordova library, which works seamlessly.

    $scope.takePicture = function(){
          Camera.getPicture().then(function(imageURI) {
            $scope.lastPhoto = imageURI;
            upload(imageURI)
          }, function(err) {
            console.err(err);
          }, {
            quality: 25,
            targetWidth: 320,
            targetHeight: 320,
            saveToPhotoAlbum: false
          });
    };

However, the upload function does not successfully submit a request to the express server.

upload = function (imageURI) {
    var ft = new FileTransfer();
    var options = new FileUploadOptions();

    options.fileKey = "photo";
    options.fileName = 'filename'; 
    options.mimeType = "image/jpeg";
    options.chunkedMode = false;
    options.httpMethod = 'put';
    options.params = { 
        "description": "Uploaded from my phone"
    };

    ft.upload(imageURI, encodeURI(RESOURCES.PRODUCTION_DOMAIN + '/api/boats/' + $scope.boat._id),
        function (e) {
            console.log('File Transfer Completed', e)
        },
        function (e) {
            alert("Upload failed", e);
        }, options);
}

I do not observe any requests reaching my server, and the console.log indicates a failure.

What could be the reason for this?

My server has the following access control methods:

    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, POST', 'PUT', 'DELETE');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header('Access-Control-Allow-Credentials', true);
    next();

I also have:

    <access origin="*"/>

In the config.xml of my app.

Why is my request failing to go through?

Edit

After running the app in x-code (after downloading the new version...), I am able to see the following error:

2015-10-26 05:00:54.955 Fish App[358:68325] File Transfer Finished with response code 404
2015-10-26 05:00:54.956 Fish App[358:68325] FileTransferError {
    body = "";
    code = 3;
    "http_status" = 404;
    source = "file:///var/mobile/Containers/Data/Application/598EAE4A-F0E4-4A3B-A4A4-0DB657981122/tmp/cdv_photo_010.jpg";
    target = "http://example.com/api/boats/";
}

It is worth mentioning that I had to adjust my nginx settings to allow for file sizes larger than 1M, only then did I receive the above error. Why is it giving a 404? The target is correct.

I have also added the following in my plist to allow all connections...

<key>NSAppTransportSecurity</key>
<dict>
  <!--Include to allow all connections (DANGER)-->
  <key>NSAllowsArbitraryLoads</key>
      <true/>
</dict>

Edit2:

I have implemented a CSP policy in my index.html which may seem like an insecure method, but I assumed it would enable me to successfully upload.

<!-- This policy allows everything (eg CSS, AJAX, object, frame, media, etc) except that 
* CSS only from the same origin and inline styles,
* scripts only from the same origin and inline styles, and eval()
-->
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; img-src '*' script-src 'self' 'unsafe-inline' 'unsafe-eval'">

Answer №1

UPDATE 2016-04-11: There is an important update from Google stating that new and updated Apps using Cordova/Phonegap must be at least version 4.1.1. For more details, please visit: Android pre-4.1.1 to be blocked

Make sure to include the white-list, plugin, and CSP, or adjust the version in your compiler accordingly.

Solving common white-list issues

An alternative to the white-list is a quick fix that eliminates the need for white-list entirely, but this may pose a security risk. Learn more about this security issue.

QUICK FIX Add the following code to your config.xml only for PHONEGAP BUILD

<preference name="phonegap-version" value="3.7.0" />

This method will be discontinued after May 2016.

THE LONG ANSWER IS as follows:

Based on Top Mistakes by Developers new to Cordova/Phonegap, you may have encountered:

  • #6 Not specifying the "phonegap version" for your compiler
  • #7 Not setting the "version" for your plugins
  • #10 Not adding the new "white-list" and "white-list plugin" parameters in config.xml.

Regarding #6 & #7

If you do not assign a version for your platform with the CLI version, or if you do not set the phonegap-version in config.xml for ''Phonegap Build'', you will automatically get the latest version. This can either work smoothly or lead to a series of errors.

For more clarity, Holly Schinsky has written a comprehensive blog post on this topic:

Cordova/PhoneGap Version Confusion

Regarding #10

This relatively new requirement implies that in order to access any website or web resources, you must utilize the whitelist and whitelist plugin. This requirement is applicable if you are using cli-5.1.1 and above. However, if your version is prior to 4.0.0, like 3.5.0 or 3.7.0, then the white-list requirement is not mandatory.

It's important to note that although the "whitelist" concept has been around for a while, the plugin and requirement are recently introduced. When the "whitelist" was introduced, the default open-access feature was deprecated, leading to a step towards its elimination.

Furthermore, the Content Security Policy (CSP) has caused confusion among developers due to lack of proper documentation. Depending on your usage and Phonegap version, the CSP might be required on every HTML page, similar to 'deviceready'. However, in some cases, it may not be necessary at all. The documentation on this topic can be challenging, so make sure to read it carefully. The information is usually buried at the end of most recent documentation pages.

Lastly, Raymond Camden highlighted a significant policy change starting with Cordova 5

Related Links

Phonegap Build Forum: Notes for upgrading to cli-5.1.1 on PGB and now required Whitelist

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps should I take to enable this SimpleModal to load automatically?

Is there a way to have the SimpleModal script load when the page loads instead of having to click a button? Thank you for your help! < div id='basic-modal' > <a href='#' class='basic'>Demo</a> </div> ...

Swap out the string variable when it is modified

To generate a string inside the "code" variable that combines the selected image values, the final code should appear similar to: "test1/A=1a/B=1b" or "test2/A=1b/B=1a", etc. If the user modifies icon "A," it should replace the value in the code instead of ...

Is it possible to bypass the confirmation page when submitting Google Form data?

Is there a way to bypass the confirmation page that appears after submitting a form? What I would like is for the form to simply refresh with empty data fields and display a message saying "your data has been submitted" along with the submitted data appea ...

Unable to convert the value "undefined" to an ObjectId (type string) in the "_id" path for the "Order" model

As someone who is new to Javascript and working on an e-commerce website, I am currently facing a challenge with displaying the order id on the return page. Each time I try to do so, I encounter an error message that reads Cast to ObjectId failed for val ...

Having trouble importing Material UI and working with ClickAwayListener

For my current project, I am utilizing material-ui to implement the functionality for changing passwords. In this root file, I am importing several child components: Personalize.js import React, { useContext, useState } from 'react'; import Cook ...

dart, setting the root directory for web application

I'm looking to include some sample websites in my web framework package. Currently, the sites work fine when running them as Dart-only implementations, but if I need to compile them to JavaScript, I have to manually move the subfolder from my package& ...

Conditional rendering is effective for displaying a form item based on certain conditions, but it may not be as effective for

I want a textarea element to appear or disappear based on the selected state of the radio buttons before it. If "no" is chosen, the textarea will be hidden, and if "yes" is chosen, the textarea will become visible. <fieldset class="input-group form-che ...

I am looking to retrieve a sophisticated/nested JSON data using jQuery

I need some assistance in fetching specific JSON object data. Specifically, I am looking to extract the name, poster image URL, size of the second backdrop image, and version number. As a newcomer to JSON, I was wondering if there is an easy way for me to ...

What causes the DOM to be updated upon each opening of the browser extension for Chrome?

Here is the default position: https://i.stack.imgur.com/tkWCA.png After checking it: https://i.stack.imgur.com/tdzbg.png When I click anywhere on the page to hide the dom extension output (without showing popup.html); However, when I reopen the extens ...

Angular JS is patient when waiting for asynchronous requests to complete

Once upon a time in a factory httpFactory.factory('setFavorability', function($http){ return{ Like: function(id){ return $http.get('http://localhost:51265/Film/Like/' + id); } } ...

A guide on calling a function from a different component in vuejs2

I am facing a situation where I need to trigger an event whenever my sidebar opens. This event should be called every time the sidebar is opened. For example, when I click on an element, it triggers the opening of my sidebar which then calls a function th ...

Binding events within other events can be achieved using D3

Trying to implement code from Scott Murray's book "Interactive Data Visualization for the Web" to create versatile bar graphs. Though the code successfully generates and updates graphs, it seems that the sorting functionality is not functioning as exp ...

JavaScript library for making HTTP requests

Can someone provide guidance on creating a JavaScript command line application that interacts with a public API using an HTTP client library? What is the preferred JavaScript HTTP library for this task? ...

A guide on extracting text content exclusively from Markdown files using Javascript

I've been working on a blogging platform with Vue that serves Markdown (*.md) files for posts. My goal is to display a list of published posts on the main page along with a preview of the first 30 words of each post. Currently, I have a function that ...

Using Cleave.js to hide the input field in an HTML form

I am currently implementing cleave.js on a website in order to create a mask that restricts input to only a 3-digit number. Here is the snippet of code I am using with cleave.js: <script> let number = new Cleave("#numberId", { ...

Using Flask to invoke a Python function that displays an image when a button is clicked

I am currently working on developing a basic web application that allows clients to upload images, processes them on the server, and then returns the processed image to be displayed in a specific div. I attempted to use ajax for this purpose, but encounter ...

Ways to terminate a running child process in npm

Within my package.json file, I have a debug script that launches a Node application. This entire NPM script is initiated by a test, and this test must terminate the debug script once it completes. When I use npm run debug and try to kill the process, the ...

FullCalendar is encountering loading issues when trying to fetch data from JSON, with the

I am currently utilizing FullCalendar to create a schedule for theater rehearsals. After considering my options, I concluded that JSON would be the most efficient way to retrieve events from my MySQL database. In the JavaScript code for the calendar page, ...

Navigating JSON Objects in Ionic 2

Example of my JSON array structure [{ label: "Interests", datatype: "check", lookupname: "null", order: "05", options: [ 0:{id: "01", value: "Photography"} 1:{id: "0 ...

Tips for retrieving data from Angular Material Table source

It's great to see everyone doing well! I'm facing an issue with rendering data to a material table, and I can't figure out why it's not working. When I try to assign the data to the table's datasource for rendering, the information ...