-
Notifications
You must be signed in to change notification settings - Fork 24.8k
Networking Guide #8381
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Networking Guide #8381
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
d3ff914
WIP
hramos 7500126
Simplified networking guide for The Basics.
hramos c12c946
Fix typo in link to WebSocket
hramos 5da9089
Remove duplicated sentence.
hramos 048ad6d
Restore some code samples, and clean up the introduction to Fetch.
hramos File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,25 +1,27 @@ | ||
--- | ||
id: basics-network | ||
title: Network | ||
title: Networking | ||
layout: docs | ||
category: The Basics | ||
permalink: docs/network.html | ||
next: more-resources | ||
--- | ||
|
||
One of React Native's goals is to be a playground where we can experiment with different architectures and crazy ideas. Since browsers are not flexible enough, we had no choice but to reimplement the entire stack. In the places that we did not intend to change anything, we tried to be as faithful as possible to the browser APIs. The networking stack is a great example. | ||
Many mobile apps need to load resources from a remote URL. You may want to make a POST request to a REST API, or you may simply need to fetch a chunk of static content from another server. | ||
|
||
## Fetch | ||
## Using Fetch | ||
|
||
[fetch](https://fetch.spec.whatwg.org/) is a better networking API being worked on by the standards committee and is already available in Chrome. It is available in React Native by default. | ||
React Native provides the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) for your networking needs. Fetch will seem familiar if you have used `XMLHttpRequest` or other networking APIs before. You may refer to MDN's guide on [Using Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) for additional information. | ||
|
||
#### Usage | ||
#### Making requests | ||
|
||
In order to fetch content from an arbitrary URL, just pass the URL to fetch: | ||
|
||
```js | ||
fetch('https://mywebsite.com/endpoint/') | ||
fetch('https://mywebsite.com/mydata.json') | ||
``` | ||
|
||
Include a request object as the optional second argument to customize the HTTP request: | ||
Fetch also takes an optional second argument that allows you to customize the HTTP request. You may want to specify additional headers, or make a POST request: | ||
|
||
```js | ||
fetch('https://mywebsite.com/endpoint/', { | ||
|
@@ -35,74 +37,46 @@ fetch('https://mywebsite.com/endpoint/', { | |
}) | ||
``` | ||
|
||
#### Async | ||
Take a look at the [Fetch Request docs](https://developer.mozilla.org/en-US/docs/Web/API/Request) for a full list of properties. | ||
|
||
#### Handling the response | ||
|
||
`fetch` returns a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that can be processed in two ways: | ||
The above examples show how you can make a request. In many cases, you will want to do something with the response. | ||
|
||
1. Using `then` and `catch` in synchronous code: | ||
Networking is an inherently asynchronous operation. Fetch methods will return a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that make it straightforward to write code that works in an asynchronous manner: | ||
|
||
```js | ||
fetch('https://mywebsite.com/endpoint.php') | ||
.then((response) => response.text()) | ||
.then((responseText) => { | ||
console.log(responseText); | ||
}) | ||
.catch((error) => { | ||
console.warn(error); | ||
}); | ||
getMoviesFromApiAsync() { | ||
return fetch('http://facebook.github.io/react-native/movies.json') | ||
.then((response) => response.json()) | ||
.then((responseJson) => { | ||
return responseJson.movies; | ||
}) | ||
.catch((error) => { | ||
console.error(error); | ||
}); | ||
} | ||
``` | ||
2. Called within an asynchronous function using ES7 `async`/`await` syntax: | ||
|
||
You can also use ES7's `async`/`await` syntax in React Native app: | ||
|
||
```js | ||
class MyComponent extends React.Component { | ||
... | ||
async getUsersFromApi() { | ||
try { | ||
let response = await fetch('https://mywebsite.com/endpoint/'); | ||
let responseJson = await response.json(); | ||
return responseJson.users; | ||
} catch(error) { | ||
// Handle error | ||
console.error(error); | ||
} | ||
async getMoviesFromApi() { | ||
try { | ||
let response = await fetch('http://facebook.github.io/react-native/movies.json'); | ||
let responseJson = await response.json(); | ||
return responseJson.movies; | ||
} catch(error) { | ||
console.error(error); | ||
} | ||
... | ||
} | ||
``` | ||
|
||
- Note: Errors thrown by rejected Promises need to be caught, or they will be swallowed silently | ||
Don't forget to catch any errors that may be thrown by `fetch`, otherwise they will be dropped silently. | ||
|
||
## WebSocket | ||
### Using Other Networking Libraries | ||
|
||
WebSocket is a protocol providing full-duplex communication channels over a single TCP connection. | ||
|
||
```js | ||
var ws = new WebSocket('ws://host.com/path'); | ||
|
||
ws.onopen = () => { | ||
// connection opened | ||
ws.send('something'); | ||
}; | ||
|
||
ws.onmessage = (e) => { | ||
// a message was received | ||
console.log(e.data); | ||
}; | ||
|
||
ws.onerror = (e) => { | ||
// an error occurred | ||
console.log(e.message); | ||
}; | ||
|
||
ws.onclose = (e) => { | ||
// connection closed | ||
console.log(e.code, e.reason); | ||
}; | ||
``` | ||
|
||
## XMLHttpRequest | ||
|
||
XMLHttpRequest API is implemented on-top of [iOS networking apis](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html) and [OkHttp](http://square.github.io/okhttp/). The notable difference from web is the security model: you can read from arbitrary websites on the internet since there is no concept of [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing). | ||
The [XMLHttpRequest API](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) is built in to React Native. This means that you can use third party libraries such as [frisbee](https://github.com/niftylettuce/frisbee) or [axios](https://github.com/mzabriskie/axios) that depend on it, or you can use the XMLHttpRequest API directly if you prefer. | ||
|
||
```js | ||
var request = new XMLHttpRequest(); | ||
|
@@ -118,38 +92,36 @@ request.onreadystatechange = (e) => { | |
} | ||
}; | ||
|
||
request.open('GET', 'https://mywebsite.com/endpoint.php'); | ||
request.open('GET', 'https://mywebsite.com/endpoint/'); | ||
request.send(); | ||
``` | ||
|
||
You can also use - | ||
> The security model for XMLHttpRequest is different than on web as there is no concept of [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing) in native apps. | ||
|
||
## WebSocket Support | ||
|
||
React Native supports [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket), a protocol which provides full-duplex communication channels over a single TCP connection. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. can we have WebSocket somewhere within our own autogenerated docs? Then you could link to that. I'm suspicious that the mozilla.org link defines a 95%-the-same-but-5%-different thing. |
||
|
||
```js | ||
var request = new XMLHttpRequest(); | ||
var ws = new WebSocket('ws://host.com/path'); | ||
|
||
function onLoad() { | ||
console.log(request.status); | ||
console.log(request.responseText); | ||
ws.onopen = () => { | ||
// connection opened | ||
ws.send('something'); | ||
}; | ||
|
||
function onTimeout() { | ||
console.log('Timeout'); | ||
console.log(request.responseText); | ||
ws.onmessage = (e) => { | ||
// a message was received | ||
console.log(e.data); | ||
}; | ||
|
||
function onError() { | ||
console.log('General network error'); | ||
console.log(request.responseText); | ||
ws.onerror = (e) => { | ||
// an error occurred | ||
console.log(e.message); | ||
}; | ||
|
||
request.onload = onLoad; | ||
request.ontimeout = onTimeout; | ||
request.onerror = onError; | ||
request.open('GET', 'https://mywebsite.com/endpoint.php'); | ||
request.send(); | ||
ws.onclose = (e) => { | ||
// connection closed | ||
console.log(e.code, e.reason); | ||
}; | ||
``` | ||
|
||
|
||
Please follow the [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) for a complete description of the API. | ||
|
||
As a developer, you're probably not going to use XMLHttpRequest directly as its API is very tedious to work with. But the fact that it is implemented and compatible with the browser API gives you the ability to use third-party libraries such as [frisbee](https://github.com/niftylettuce/frisbee) or [axios](https://github.com/mzabriskie/axios) directly from npm. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
{ | ||
"title": "The Basics - Networking", | ||
"description": "Your app fetched this from a remote endpoint!", | ||
"movies": [ | ||
{ "title": "Star Wars", "releaseYear": "1977"}, | ||
{ "title": "Back to the Future", "releaseYear": "1985"}, | ||
{ "title": "The Matrix", "releaseYear": "1999"}, | ||
{ "title": "Inception", "releaseYear": "2010"}, | ||
{ "title": "Interstellar", "releaseYear": "2014"} | ||
] | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
+1