简体   繁体   中英

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:

我的警报现在

What do I do wrong ?

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)
}

You're not consuming your promise , try :

  componentWillMount: function(){
    fetch('/fimlList')
    .then(function(response) {
      return response.json()
    })
    .then(function(responseJson) {
       alert(responseJson.myString);
    })
  },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM