使用 fetch 从 express 获取数据

Get data from express with fetch

我尝试 alert 在 express.get 中可变的字符串并执行 res。我想提醒这个 "I am working fetch"。

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

以及我得到的:

我做错了什么?

您没有兑现您的承诺,请尝试:

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

您为 fromServer 分配了来自 fetch 的承诺... 您尝试按同步方式编写代码,而实际上它是异步的

要么将代码移到最后一个 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/await 方法,我会建议更像这样的方法:

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