使用fetch从express获取数据

时间:2016-10-24 20:35:26

标签: javascript express reactjs fetch

我尝试alert在express.get中变量的字符串并执行res。我想要警惕这个"我正在工作取得"。

这是我的 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');

我的 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;

我得到了什么:

My alert now

我做错了什么?

2 个答案:

答案 0 :(得分:5)

您为fromServer分配来自获取的承诺... 您试图以同步方式编写代码,而事实上它是异步的

将代码移到最后then函数

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

或使用async / await在编写代码时获得同步感觉

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

    alert(fromServer);
}

如果你采用异步/等待方法,我会建议更像这样的东西:

async function(){
    let response = await fetch('/fimlList')
    let responseJson = await response.json()
    let fromServer = responseJson.myString
    alert(fromServer)
}

答案 1 :(得分:2)

你没有消费你的承诺,试试:

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