Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get data from express with fetch

I try to alert string which is variable in express.get and do to res. I wanna get in alert this "I am working fetch".

Here my server.js

var express = require('express');
var app = express();

app.use(express.static(__dirname + '/publicServer'));

app.get('/fimlList', function(req, res) {
  console.log('i receive a GET request');

  var tryFetch = {myString: 'I am working fetch'};

  res.json(tryFetch)
})

app.listen(3000);
console.log('Server running on port 3000');

my App.js

import React from 'react';

var IchBinForm = require('./IchBinForm');
var SortFilms = require('./SortFilms');
var SearchFilm = require('./SearchFilm');
var FilmShort = require('./FilmShort.js');
var FilmLong = require('./FilmLong.js');

var App = React.createClass({
  getInitialState: function() {
    return {
      list: {}
  },

  componentWillMount: function(){
    var fromServer = fetch('/fimlList')
    .then(function(response) {
      return response.json()
    })
    .then(function(responseJson) {

      return responseJson.myString
    })

    alert(fromServer);

  },

changeShow: function(newShow, filmId) {...},    
  deleteFilm: function(id) {...},    
  seeForChangeInForm: function(change, id) {...},    
  addNewFilm: function() {...},   
  sortMe:function() {...},    
  searchMe: function(searchWord) {...},    
  howSearch:function(whichCheckBox, val) {...},

  render: function() {

    ....
        }
      }

    });

    return (...);
  }
});

module.exports = App;

and what I get:

My alert now

What do I do wrong ?

like image 862
Kirill Stas Avatar asked Oct 24 '16 20:10

Kirill Stas


People also ask

Does fetch work with Express?

Since fetch is a web API, you will not be able to use it on server code. Although there is an npm package that can help you utilize the capabilities of fetch while writing Express code.

Does fetch works in Nodejs?

The developer does not have to install npm before doing networking on Node. The native Fetch API will make HTTP fetching in node environments feel much more seamless and natural. If a developer already has experience using the Fetch API, they will have no problem using the Node. js integration.

What is the correct way to get data using fetch () method?

Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.

Is fetch deprecated?

Request is fully deprecated requiring us to switch libraries (see #414 for more information).


2 Answers

You assign fromServer with a promise from fetch... You try to write code as it was synchronously while in fact it's asynchronously

Either move the code inside the last then function

.then(function(responseJson) {
    console.log(responseJson)
})

or use async/await to get a synchronously feeling while writing code

async function(){
    var fromServer = await fetch('/fimlList')
    .then(function(response) {
      return response.json()
    })
    .then(function(responseJson) {
      return responseJson.myString
    })

    alert(fromServer);
}

if you go by the async/await approach i would suggest something more like this:

async function(){
    let response = await fetch('/fimlList')
    let responseJson = await response.json()
    let fromServer = responseJson.myString
    alert(fromServer)
}
like image 163
Endless Avatar answered Sep 18 '22 09:09

Endless


You're not consuming your promise , try :

  componentWillMount: function(){
    fetch('/fimlList')
    .then(function(response) {
      return response.json()
    })
    .then(function(responseJson) {
       alert(responseJson.myString);
    })
  },
like image 40
maioman Avatar answered Sep 21 '22 09:09

maioman