Giter Site home page Giter Site logo

futurepress / react-native-static-server Goto Github PK

View Code? Open in Web Editor NEW
352.0 10.0 175.0 1.25 MB

HTTP static file server for React Native

License: MIT License

Java 35.32% JavaScript 9.40% Objective-C 28.31% HTML 1.67% Ruby 13.80% TypeScript 7.11% Starlark 4.39%
react-native

react-native-static-server's Introduction

react-native-static-server

A cross platform component for serving static assets with React Native.

Getting started

$ npm install react-native-static-server --save

Installation

From react-native 0.60 autolinking will take care of the link step but don't forget to run pod install

$ react-native link react-native-static-server

Usage

Declare the StaticServer with a port or use the default 0 to pick a random available port.

import StaticServer from 'react-native-static-server';

let server = new StaticServer(8080);

// Start the server
server.start().then((url) => {
  console.log("Serving at URL", url);
});

// Stop the server
server.stop();

// Check if native server running
const isRunning = await server.isRunning()
// isRunning - true/false

StaticServer serves from the document directory (default) or takes an optional absolute path to serve from.

For instance, using react-native-fs you can get the document directory and specify a directory from there.

Default (document directory)

import StaticServer from 'react-native-static-server';
import RNFS from 'react-native-fs';

// create a path you want to write to
let path = RNFS.DocumentDirectoryPath + '/www';

let server = new StaticServer(8080, path);

Custom folder (iOS)

Create the folder for static files

Create a folder in your project's top-level directory (usually next to your node_modules and index.js file), and put the files you want to access over http in there.

Add folder (static files) to XCode

This folder must be added to XCode so it gets bundled with the app.

In XCode, Project Navigator right click in the folder project → Add files to "<project>" → Select the static folder and clic options (Uncheck copy items if needed, Create folder references) so don't duplicate files → Clic Add.

When the app gets bundled, this folder will be next to the compiled app, so using MainBundlePath property from react-native-fs you can access to the directory.

import StaticServer from 'react-native-static-server';
import RNFS from 'react-native-fs';

// path where files will be served from (index.html here)
let path = RNFS.MainBundlePath + '/www';

let server = new StaticServer(8080, path);

If the server should only be accessible from within the app, set localOnly to true

import StaticServer from 'react-native-static-server';

// Just set options with defaults
let server = new StaticServer({localOnly : true });
// Or also valid are:
let server = new StaticServer(8080, {localOnly : true });
let server = new StaticServer(8080, path, {localOnly : true });

If the server should not pause when the app is in the background, set keepAlive to true

let server = new StaticServer({keepAlive : true });

Passing 0 as the port number will cause a random port to be assigned every time the server starts. It will reset to a new random port each time the server unpauses, so this should only be used with keepAlive.

let server = new StaticServer(0, {keepAlive : true });

Credits

Thanks to CorHttpd and react-native-httpserver for the basis of this library.

react-native-static-server's People

Contributors

bahaa96 avatar fchasen avatar frangeris avatar godefroy avatar gvanderclay avatar hengkx avatar josuesilva-hotmart avatar kesha-antonov avatar mayank-baiswar avatar nickpisacane avatar onedevlad avatar prasannavl avatar sampsasaarela avatar smellman avatar tsemerad avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-static-server's Issues

Remove .git folder from npm registry

Seems that .git -folder is added to npm registry and I think it shouldn't be there.

Now this package causes react-native-static-server: Appears to be a git repo or submodule -error when try to perform react-native-git-upgrade and react-native-static-server is installed from npm registry.

Solution is to manually remove node_modules/react-native-static-server/.git -folder or install package directly from github.

There are several files providing this module. after install static-server.

// everything is the latest version for today
npm install --save react-native-static-server
react-native link react-native-static-server

react-native android-run
Loading dependency graph, done.
Bundling index.js [development, non-minified] 0.0% (0/1), failed.

error: bundling failed: ambiguous resolution: module C:\Users\unknown\test\index.js tries to require react-native, but there are several files providing this module. You can delete or fix them:

  • C:\Users\unknown\test\node_modules\react-native-static-server\node_modules\react-native\package.json
  • C:\Users\unknown\test\node_modules\react-native\package.json

Do you know what could be the root cause of the problems?

Thank you,

Accessing static assets from a WebView

One obvious reason one would want to run a local server in a react native app would be to load static assets in a WebView... so I'm wondering if you have that kind of sample or experiment any of that?

I am trying to load an html in a WebView on iOS and getting the error below:

screen shot 2017-12-13 at 16 25 31

URL is (null)://(null):(null)

Hey !

I've an issue when i'm building on a IOS device (iPhone 6s Plus) :

The server start at (null)://(null):(null) so nothing works.

The config (works great in simulator) :

let server = new StaticServer(8080, RNFS.DocumentDirectoryPath); server.start().then((url) => { alert('Server started at ' + url) });

Note : it happens only if WIFI is turned off

Any idea ?

Regards

error: package com.reactlibrary does not exist

:app:compileDebugJavaWithJavac - is not incremental (e.g. outputs have changed, no previous execution, etc.).
/home/upyun/impress-webview/android/app/src/main/java/com/impress_webview/MainApplication.java:17: error: package com.reactlibrary does not exist
import com.reactlibrary.FPStaticServerPackage;
                       ^
/home/upyun/impress-webview/android/app/src/main/java/com/impress_webview/MainApplication.java:33: error: cannot find symbol
          new FPStaticServerPackage(),
              ^
  symbol: class FPStaticServerPackage
2 errors
:app:compileDebugJavaWithJavac FAILED

FAILURE: Build failed with an exception.

How to stop server when start.server() is called within function?

Imagine I have a function within a component

export default class Test extends Component {

    ...
    _startServer = () => {
        server
            .start()
            .then((localServer) => {
                this.setState({
                    serverRunning: true,
                    localServer: localServer
                })
            });
     }

     _stopServer = (refToServer) => {
         refToServer.stop();
     }

     ...

    render() {
        return (
            <TouchableOpacity
                onPress={() => this._startServer()} />
     
            <TouchableOpacity
                onPress={() => this._stopServer(??)} />
        )
    }
}

How would I pass the _stopServer() function the reference to the server that it knows, what to stop?

Android: how to serve statics from assets folder?

I did some tests and right now there's no way to point the StaticServer to a 'www_root' on the assets folder on Android. I think storing the static files as assets is a straightforward way, but I couldn't find a way to make it work.

Any ideas?

p.s. RNFS.DocumentDirectoryPath is not where the assets are stored

Allow server to run in the background

Hello and thanks for a great library. It works fantastic.

I am just curious if it is somehow possible to allow the server to run while the app is in the background. I am using the library for redirection purposes, so the user opens a browser which then opens the localhost where my static file is. The problem is that as fast as I leave the app, the server shuts down.

Thanks in advance.

Refactor StaticServer constructor

Hi

This is a suggestion,
Too many conditions check in constructor, my suggestion below

let server = new StaticServer({port: 8080, localOnly : true, keepAlive : true });

class StaticServer {
          constructor(opts) {
                       if(opts)
                        {
				this.port = `${opts.port}` || PORT;
				this.root = opts.root || ROOT;
				this.localOnly = opts.localOnly || false;
				this.keepAlive = opts.keepAlive || false;
			 }
			else{
				this.port = PORT;
				this.root = ROOT;
				this.localOnly = false;
				this.keepAlive = false;
                   }
             }

....
}

let me know your feedback

FPStaticServer is undefined (Android)

Hi,

I am using React Native 0.57.5 and react-native-static-server 0.3.0.
The constructor of the rn static server runs without problems. When the code reaches to call the native module FPStaticServer.start it throws an exception saying that the FPStaticServer object is undefined.
I guess there is a problem in the native module link with the javascript.
Anyone with similar problems or a solution to this one?

How add the `www` folder so code can access in runtime?

First, thanks the lib 👍

I'm having some issues trying to access to the index.html from the browser, everything seems to be working fine but I can't get it running pointing to my www folder, I know there is not issue with the lib, the error is This 192.168.1.36 page can’t be found because locally inside the app, the folder where my index file should be, not exists, so I'm passing the path like this:

    let path = fs.DocumentDirectoryPath + '/embeded'
    console.log(path)
    let server = new StaticServer(9191, path)
      server.start().then((url) => {
      console.log("Serving at URL", url);
    })

And my folder structure:
screen shot 2017-06-24 at 5 02 53 pm

But when I check inside the final "temporal folder" in the simulator, I don't see the embeded folder, so is not finding the index.html because the folder do not exists.

I already tried adding the folder to my xcode project, trying that the folder gets created inside the bundle app, but didn't work:
screen shot 2017-06-24 at 5 06 06 pm

This is a cry for help... any advice?

Thanks

Build fails on React-Native 0.56

Build fails on a fresh install of React Native 0.56 with react-native-static-server. Seems like resources are missing.

:react-native-static-server:preBuild UP-TO-DATE
:react-native-static-server:preReleaseBuild UP-TO-DATE
:react-native-static-server:checkReleaseManifest
:react-native-static-server:preDebugAndroidTestBuild UP-TO-DATE
:react-native-static-server:preDebugBuild UP-TO-DATE
:react-native-static-server:preDebugUnitTestBuild UP-TO-DATE
:react-native-static-server:preReleaseUnitTestBuild UP-TO-DATE
:react-native-static-server:prepareAndroidArchLifecycleRuntime100Library
:react-native-static-server:prepareComAndroidSupportAnimatedVectorDrawable2610Library
:react-native-static-server:prepareComAndroidSupportAppcompatV72610Library
:react-native-static-server:prepareComAndroidSupportSupportCompat2610Library
:react-native-static-server:prepareComAndroidSupportSupportCoreUi2610Library
:react-native-static-server:prepareComAndroidSupportSupportCoreUtils2610Library
:react-native-static-server:prepareComAndroidSupportSupportFragment2610Library
:react-native-static-server:prepareComAndroidSupportSupportMediaCompat2610Library
:react-native-static-server:prepareComAndroidSupportSupportV42610Library
:react-native-static-server:prepareComAndroidSupportSupportVectorDrawable2610Library
:react-native-static-server:prepareComFacebookFbuiTextlayoutbuilderTextlayoutbuilder100Library
:react-native-static-server:prepareComFacebookFrescoDrawee190Library
:react-native-static-server:prepareComFacebookFrescoFbcore190Library
:react-native-static-server:prepareComFacebookFrescoFresco190Library
:react-native-static-server:prepareComFacebookFrescoImagepipeline190Library
:react-native-static-server:prepareComFacebookFrescoImagepipelineBase190Library
:react-native-static-server:prepareComFacebookFrescoImagepipelineOkhttp3190Library
:react-native-static-server:prepareComFacebookReactReactNative0560Library
:react-native-static-server:prepareComFacebookSoloaderSoloader030Library
:react-native-static-server:prepareOrgWebkitAndroidJscR174650Library
:react-native-static-server:prepareReleaseDependencies
:react-native-static-server:compileReleaseAidl
:react-native-static-server:compileReleaseNdk NO-SOURCE
:react-native-static-server:compileLint
:react-native-static-server:copyReleaseLint NO-SOURCE
:react-native-static-server:compileReleaseRenderscript
:react-native-static-server:generateReleaseBuildConfig
:react-native-static-server:generateReleaseResValues
:react-native-static-server:generateReleaseResources
:react-native-static-server:mergeReleaseResources
:react-native-static-server:processReleaseManifest
:react-native-static-server:processReleaseResources
/home/pvl/workspace/repo/htone/htone/node_modules/react-native-static-server/android/build/intermediates/res/merged/release/values-v24/values-v24.xml:3: AAPT: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'.
    
/home/pvl/workspace/repo/htone/htone/node_modules/react-native-static-server/android/build/intermediates/res/merged/release/values-v24/values-v24.xml:4: AAPT: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Colored'.
    
/home/pvl/workspace/repo/htone/htone/node_modules/react-native-static-server/android/build/intermediates/res/merged/release/values-v26/values-v26.xml:15:21-54: AAPT: No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
    
/home/pvl/workspace/repo/htone/htone/node_modules/react-native-static-server/android/build/intermediates/res/merged/release/values-v24/values-v24.xml:3: error: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'.

/home/pvl/workspace/repo/htone/htone/node_modules/react-native-static-server/android/build/intermediates/res/merged/release/values-v24/values-v24.xml:4: error: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Colored'.

/home/pvl/workspace/repo/htone/htone/node_modules/react-native-static-server/android/build/intermediates/res/merged/release/values-v26/values-v26.xml:15: error: Error: No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.


:react-native-static-server:processReleaseResources FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':react-native-static-server:processReleaseResources'.
> com.android.ide.common.process.ProcessException: Failed to execute aapt

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

missing deflate

Heya

Just trying to build this into my project. I'm getting missing symbols "_deflate", "_inflate", "_defaultEnd" and a few others.

Is this from zlib ? How should I link them in ?!

Thanks!

Jonah

Response 304

Original issue in NanoHttpd repo

I have RN app with WebView that shows local stored files via react-native-static-server. I run and stop server every time when WebView is created. On iOS it works fine, but on Android server returns 304 response like described in original issue.

Can you implement any solutions for this problem? May be it can be a some flag or property of server that turns on and off it solution. Thank you!

A problem occurred configuring project ':app'.

After installing react-native-static-server I keep getting this error.
A problem occurred configuring project ':app'.

Could not resolve all dependencies for configuration ':app:_debugApk'.
Configuration with name 'default' not found.

Wrong Android linking instructions

The instruction from here say:

Open up android/app/src/main/java/[...]/MainActivity.java
Add import com.futurepress.staticserver.FPStaticServerPackage; to the imports at the top of the file
Add new FPStaticServerPackage() to the list returned by the getPackages() method

However, imports are usually done in android/app/src/main/java/[...]/MainApplication.java from what I've seen with other RN projects that need linking. Also, the getPackages method only exists in MainApplication.java.

a problem on android

Hello, how can in android www be added to the project
INTERNAL ERROR: given path is not a directory (/data/user/0/com.reactappdemo/files/www).

Breaking changes?

I installed the server as suggested and linked it automatically.
I then try to run the minimal example


import StaticServer from 'react-native-static-server';
let server = new StaticServer(8080);
server.start().then((url) => {
  console.log("Serving at URL", url);
});

However, that gives me this error as soon as I start the App on Android (it works on iOS):

name == null Screenshot error

It points me to FPStaticServerModule.java, line 101 which says
www_root = new File(this.reactContext.getFilesDir(), root);
I am not sure what to make of it.

I checked if the linking was correct and the only difference between automatic- and manual linking is that the docs say
"add this line import com.reactlibrary.FPStaticServerPackage; in android/app/src/main/java/[...]/MainActivity.java" while the automatic linking inserts import com.futurepress.staticserver.FPStaticServerPackage; into MainApplication.java. Looking at the MainApplication.java file I see many other libraries linked there, so I assume thats correct. In MainApplication.java I tried exchanging the line import com.futurepress.staticserver.FPStaticServerPackage; as thedocs suggest with import com.reactlibrary.FPStaticServerPackage;. No luck.
The error was reported here too #5

yarn: 1.0.2
react-native-cli: 2.0.1
react-native: 0.48.3
npm: 5.3.0

Where could the error come from? I tried installing the sever on a fresh initialized project and got the same error.

Creating Static Server Offline

Been using your plugin for a while and love it, but I've ran into a big problem. When all internet / wifi has been turned on I cannot start the server.

Error: StaticServer could not start

Any ideas how I can get around this?

Thanks

Server is not alive after iOS device is 'locked'

keepAlive works fine when the app is in the background, however when the device is locked or goes into standby the server is no longer running in the background, or when the app is put into the foreground again.

Not sure if keepAlive is meant to support this or not, I am considering starting the server again manually once the app is 'active' as a work around for now.

localhost with {keepAlive: true} issue

On a physical IOS ipad, localhost with port 8081, 8082, 8083 and with {keepAlive: true} and the asset I wanna serve doesn't open in safari. Is this because of debug mode. Will it work after producing a signed build. Any suggestions of this is appreciated. Thanks.

If server is already running, return the serverUrl

Hi

I found this issue of server already running looks difficult to keep track of server status on RN.

so its better to return serverUrl if server is already started, rather than throw error or warning

// in FPStaticServer.m

// instead of these lines
if(_webServer.isRunning != NO) {
        NSError *error = nil;
        reject(@"server_error", @"StaticServer is already up", error);
        return;
    }

// return server url
if(_webServer.isRunning != NO) {
        RCTLog(@"server already starting: %@", self.url);
        resolve(self.url);
        return;
   }

and in index.js

// remove commented lines, as it will return the server url if its already running
start() {
		// if( this.running ){  
		//	return console.warn('StaticServer already running');
		// }

		this.started = true;
		this.running = true;

		if (!this.keepAlive && (Platform.OS === 'android')) {
			AppState.addEventListener('change', this._handleAppStateChange.bind(this));
		}

		return FPStaticServer.start(this.port, this.root, this.localOnly, this.keepAlive);
	}

also same thing for stop, don't throw the warning if its not running, as it will do nothing in FPStaticServer.m

// please remove commented lines
stop() {
		// if( !this.running ){
		//	return console.warn('StaticServer not running');
		// }

		this.running = false;
		return FPStaticServer.stop();
}

also better not keep track of running status in index.js, let FPStaticServer.m handle it.

Let me know your comments, happy to submit a PR if you are ok with above changes

(Android) Serve files from assets?

Hi and thanks for this nice RN module!

This might be stupid question, but I wonder if it's possible to serve html/js/css-files from assets? (in Android)

So if I use filesystem, I'm using file:///android_asset/web/index.html-uri in WebView but I would like to use http://127.0.0.1:8080 as an uri with react-native-static-server serving files from that assets path.

If it's not possible to do that, what is the best way to copy files from assets to /data/data/com.xxx/files/whatever?

This seems to be very simple with iOS where you can just use "MainBundlePath"/whatever as a path and put your html/js/css-files in that folder.

keepAlive = true, new Version not in yarn?

I installed react-native-static-server before the keepAlive option was available. I tried yarn update react-native-static-server, which did not update to the version that is on git. Is it known to yarn that there is a new version of this nice library out there?

{localOnly: true} option issue

Removing {localOnly: true} option on an IPhone 6 - IOS 11.2 simulator or even on an android simulator/physical device doesn't seem to open the files I wanna serve in safari or chrome or any browser, but it can serve the files through a webview on the app itself. Correct me if I'm wrong but is this what removing this option expected. Any suggestions on how to proceed next is appreciated. Thanks!

46 Duplicate symbols for architecture x86_64

Any idea why building in Xcode is giving me this issue?
screen shot 2017-05-11 at 12 40 48 pm

I'm using a detached Expo project, which uses Pods for some native dependencies, and then I'm including the React headers from the Pod folder in the Header Search Path. Here's what the header search paths look like:
screen shot 2017-05-11 at 12 45 02 pm

Thanks in advance!

Android Not Serving Website

Hi,

My app works correct on IOS but fails on Android. The assets have been downloaded and stored onto the device, that are located here /data/user/0/com.springboard/files/11 and then served via the Static Server.

The path the assets are download to is RNFS.DocumentDirectoryPath + '/11'

          RNFS.exists(RNFS.DocumentDirectoryPath + '/11').then((result)=> {
                //Check files are there..
                if(result){
                    webserver = new StaticServer(8080, RNFS.DocumentDirectoryPath + '/11/index.html')
                    webserver.start().then((url) => {
                        dispatch({type: types.APP_VISABILITY, payload: url})
                    })
                }
            })

But when the web view is loaded it seems to have the error
"net::ERR_CONNECTION_REFUSED"

Any ideas?

Redirection

Is there any way to redirect all requests to index.html, for example? Or any other approach to this?

Server not running when app is in background

Hi

Thanks for the great library.

When the app is in background the server is not running, i have started with below setting

let server = new StaticServer(8080, path, { keepAlive: true });

after going through the GCDWebServer documentation, we need to set GCDWebServerOption_ConnectedStateCoalescingInterval

[options setObject:@2.0 forKey:GCDWebServerOption_ConnectedStateCoalescingInterval];

Ref swisspol/GCDWebServer#333

can you please provide this option to set duration to keep running when app is in background

expose webServer.serverURL property

Hi

Can you please expose server url property so when server is already running, we can access the url without starting it again.

// example use case
let server = new StaticServer(8080, path, { keepAlive: true });

if (!server.running) {
            var url = await server.start();
            console.log("Server URL", url);
} else {
           // get server url 
       var url = server.serverUrl;  
}

One more question => Should we have only single instance of server with in the app? What is server initialization recommendation?

support for cross domain requests

Is there a way to allow cross domain requests? I have tried to set Access-Control-Allow-Origin but not found how do that. is there any other way?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.