Kirill Stas Kirill Stas - 1 year ago 173
React JSX Question

React + fetch request

I am reading this article fetch API and trying to understand how to work with fetch in React. Firstly, could you explain what is request headers ?

in angular we do something like:

$http.get('/someword').success(function(response) {
console.log('i got the data i requested');
var variable = response;

and than on server side in express I can write:

var app = express();
app.get('/thissomeword', function(req, res) {
console.log('I got a GET request')

How to do the same with fetch ? And the main question where and when I need to do it ? I understand that i need after i get data to do this.setState({}) for using my data later, but HOW is for me huge conundrum.

Answer Source

Here you have great facebook documentation: with example that shows what you want

headers in request

Sometimes you need header in request to provide access token or content-type (especially in POST request)

fetch('', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',

Promises instead of callbacks

In your example you pass callbacks (req and res) to your request, in fetch you have Promises so you get response as a paramether of then or error message in catch.

  .then((response) => response.json())
  .then((responseJson) => {
    return responseJson.movies;
  .catch((error) => {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download