使用fetch从express获取数据

7

我试图在express.get中使用变量来alert字符串,并将其传递给res。我希望在alert中显示"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;

我得到的是什么:

现在我的警报

我做错了什么?


1
警告需要在最后一个 .then() 中。数据是异步到达的... - Kevin
我已经完成了,但是它返回了未定义。 - Kirill Stas
1
尝试记录responseJson而不是警报responseJson.myString,看看你得到了什么。 - Endless
1
你可能拼错了 fimlList?应该是 filmList 吗? - Endless
它在服务器和应用程序中类似。 - Kirill Stas
2个回答

5
你把fromServer赋值为从fetch获得的promise... 你试图编写同步代码,但实际上它是异步的。
要么将代码移动到最后一个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)
}

我做了,但它返回未定义。这是什么意思? - Kirill Stas
是的,你很有趣。但我知道 undefined 是什么意思,当我说“这是什么意思”时,实际上我的意思是“为什么它返回 undefined?”抱歉误解了。 - Kirill Stas
也许您可以更新您的问题示例或提供编辑,以便我们可以看到您实际拥有的内容。可能是打字错误或类似的问题。如果您按照建议操作,它应该可以正常工作。 - Kevin

2

您没有消耗您的Promise,尝试:

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

我得到的是:localhost:3000显示为undefined。 - Kirill Stas
什么是区别? - Kirill Stas
它不应将响应序列化,但在你的情况下,你正在fetch方法中解析它,所以这并不适用... - maioman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接