簡體   English   中英

使用fetch從express獲取數據

[英]Get data from express with 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;

我得到了什么:

我的警報現在

我做錯了什么?

分配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 / await方法,我會建議更像這樣的東西:

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

你沒有消耗你的承諾,試試:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM