尝试在客户端访问来自服务器的 API 响应

Trying to access API response from server on client-side

我正在尝试从 Twitter 获取一些数据以在客户端进行操作。我正在使用 twit 访问数据。

我有一个节点服务器,我称之为 server.js,然后有一个 React 前端,我称之为 index.js.

如果我 运行 server.js 上的以下代码,它会在控制台中记录返回的数据(推文):

T
  .get('statuses/user_timeline', { skip_status: true })
  .catch(function (err) {
    console.log('caught error', err.stack)
  })
  .then(function (result) {
    // `result` is an Object with keys "data" and "resp"
    console.log(result.data)
  })

(其中 Tconst T = new Twit({ ... })

所以我知道这行得通。


我想要做的是让 index.js 像这样从服务器调用数据:

componentDidMount() {
  fetch('http://localhost:3000/internal-api/twitter/')
    .then(data => {
      console.log(data)
    })
}

然后我在 server.js 中设置代码如下:

app.get('/internal-api/twitter/', (req, res) => {
  T
    .get('statuses/user_timeline', { skip_status: true })
    .then(function(result) {
      // `result` is an Object with keys "data" and "resp"
      console.log(result.data)
      res.send(result.data)
    })
    .catch(function(err) {
      console.log('caught error', err.stack)
      res.send({ error: err })
    })
})

但是,当我 运行 index.js 服务器端和浏览器控制台没有任何记录时,会记录 result.data

Response {
  body: (...)
  bodyUsed: false
  headers: Headers {}
  ok: true
  redirected: false
  status: 200
  statusText: "OK"
  type: "basic"
  url: "http://localhost:3000/internal-api/twitter/"
  __proto__ : Response
}

知道我做错了什么吗?我很乐意提供更多代码,我只是不想把问题搞得一团糟。

感谢任何帮助,谢谢!

更新:以下是server.js的全部内容。

const express = require('express')
const path = require('path')

const app = express()
const PORT = process.env.PORT || 5000

var Twit = require('twit')

const T = new Twit({
  consumer_key: 'XXXXXXXX',
  consumer_secret: 'XXXXXXXX',
  access_token: 'XXXXXXXX',
  access_token_secret: 'XXXXXXXX'
})

app.get('/internal-api/twitter/', (req, res) => {
  T
    .get('statuses/user_timeline', { skip_status: true })
    .then(function(result) {
      // `result` is an Object with keys "data" and "resp"
      console.log(result.data)
      res.send(result.data)
    })
    .catch(function(err) {
      console.log('caught error', err.stack)
      res.send({ error: err })
    })
})

// Priority serve any static files.
app.use(express.static(path.resolve(__dirname, '../react-ui/build')));

// Answer API requests.
app.get('/api', function (req, res) {
  res.set('Content-Type', 'application/json');
  res.send('{"message":"Hello from the custom server!"}');
});

// All remaining requests return the React app, so it can handle routing.
app.get('*', function(request, response) {
  response.sendFile(path.resolve(__dirname, '../react-ui/build', 'index.html'));
});

app.listen(PORT, function () {
  console.log(`Listening on port ${PORT}`);
});

您必须在客户端调用 .then((response) => response.json()) 以读取流以完成:

The json() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON.

componentDidMount() {
  fetch('http://localhost:3000/internal-api/twitter/')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(err => console.log(err));
}

此外,您不应使用自己的 serializer,因为如果您使用数据调用 res.send()express 可以自动为您执行此操作:

app.get('/internal-api/twitter/', (req, res) => {
  T
    .get('statuses/user_timeline', { skip_status: true })
    .then(function(result) {
      // `result` is an Object with keys "data" and "resp"
      console.log(result.data)
      res.send(result.data)
    })
    .catch(function(err) {
      console.log('caught error', err.stack)
      res.send({ error: err })
    })
})