【问题标题】:Call an API using superagent?使用超级代理调用 API?
【发布时间】:2017-03-22 01:18:47
【问题描述】:

我有一个包含这个数据分支的 API

{
  "data": {
    "id": ,
    "title": ,
    "description": ,
    "old_price": "100",
    "new_price": "50",
    "size": "50",
    "quantity": 20,
  },
  "errors": null,
  "code": 1
}

我正在使用 superagent 来调用 API 并呈现此信息,但我做错了。

这是我的代码

import React from 'react';
import {render} from 'react-dom';
import superagent from 'superagent';
import Layout from './components/Layout';

class App extends React.Component{
  constructor(){
    super()
    this.state={
      name:''
    }
  }
    componentDidMount(){
        console.log('componentDidMount');

        const url='http://...';
        superagent
        .get(url)
        .query(null)
        .set('Accept', 'application/json')
        .end ((error, response)=>{
            const title=response.body.response
            console.log(JSON.stringify(title));
            
            this.setState({
              name:title
            })
        })
        
    }
  render(){
    return(
      <Layout data={this.state}/>
    )
  }
}


render(<App />, document.getElementById('app'));

我在这里渲染它

import React from 'react';

export default class Layout extends React.Component{
    render(){
        let data = this.props.data;
        return (
            <div> 
                 {data.name}
            </div>
        )
    }
}

但不是渲染,我认为我做错了。请你帮我解决这个问题。

【问题讨论】:

    标签: api reactjs superagent


    【解决方案1】:
    const title=response.body.response
    

    应该是

    const title=response.body
    

    很有可能

    【讨论】:

    • 嘿,谢谢你成功了!当然,我做了一些调整,但这是一个起点)
    【解决方案2】:

    对我来说,这样的事情是有效的:

    import request from 'superagent';
    
    getFooFromServer() {
      const url='http://...';
      request.get(`${url}/foo`)
        .accept('json')
        .then(res => {
          //Do something with your data
        }
        catch(error => {
          //Do something with the error
        };
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 2021-07-03
      • 2020-01-03
      • 1970-01-01
      • 2018-02-12
      • 2015-02-17
      • 1970-01-01
      相关资源
      最近更新 更多