【问题标题】:Can't read my API or particular API [React.js/Node.js/Axios/Fetch]无法读取我的 API 或特定 API [React.js/Node.js/Axios/Fetch]
【发布时间】:2017-12-29 13:03:12
【问题描述】:

我对此感到非常困惑,如果你告诉我我的代码有误,我已经尝试了不同的 API 并且它可以工作。但是在我的例子中,有几个 API 无法在 react.js 中访问。请帮助我并纠正。您可以尝试这些在 react.js 中不起作用但总是出现 typescript fetching failed 或网络错误的 API:

  1. http://pp53.azurewebsites.net/pp53service.svc/viewprovincelist
  2. https://www.getpostman.com/collections/1d8df8b0b5bf27e5009b

第一个是我的 API,第二个是其他的。我已经在 Postman 以及其他编程语言和其他框架(如 ASP.NET MVC)中尝试过该 API,但它不再遇到麻烦了。但是当我用 axios 尝试 react.js 时,获取,甚至 ajax,API 都不起作用。有没有人可以向我解释为什么?因为如果你用这个https://api.myjson.com/bins/1cfkej或者这个http://jsonplaceholder.typicode.com/todos都没有问题。

谢谢!!

这是我的代码

import React from 'react';
import axios from 'axios';

export class viewDetailPP53 extends React.Component {
    constructor(props) {
        super(props);
        this.state = { count : [] };        
    }

    componentDidMount(){
        var self = this;
        axios.get('http://pp53.azurewebsites.net/pp53service.svc/viewprovincelist')
        .then(function (results) {
            self.setState({ count: results.data });
        })
        .catch(function (error) {
            console.log(error);
        });
    }

    render() { 
        return(
            <div>
                <table>
                    <thead>
                        <tr>
                            <th>column 1</th>
                            <th>column 2</th>
                        </tr>          
                    </thead>
                    <tbody>
                        {this.state.count.map((a, i) => <TableRow key = {i} count = {a} />)}
                    </tbody>
                </table>
            </div>
        );
    }
}

class TableRow extends React.Component {
   render() {
      return (
         <tr>
            <td>{this.props.count.idProvince}</td>
            <td>{this.props.count.province}</td>
         </tr>
      );
   }
}

【问题讨论】:

标签: javascript node.js reactjs axios wcf-rest


【解决方案1】:

感谢Dimitar Dimitrov 提供线索。我现在解决了我的问题。这是因为我自己的 API 没有为 CORS 配置。我只是通过添加这一行来启用它:

<httpProtocol>  
      <customHeaders>  
        <add name="Access-Control-Allow-Origin" value="*" />  
      </customHeaders>  
</httpProtocol>

在我的 WCF RESTful web.config 和 system.webserver 下。 参考:http://www.c-sharpcorner.com/UploadFile/dhananjaycoder/solved-access-control-allow-origin-error-in-wcf-rest-service/

非常感谢您节省了我的时间:)

【讨论】:

  • 很高兴我能帮上忙,我删除了我的答案,因为我觉得我需要更深入地解释一下,不幸的是没有时间:)
猜你喜欢
  • 1970-01-01
  • 2019-06-27
  • 2021-01-01
  • 2021-08-22
  • 1970-01-01
  • 1970-01-01
  • 2020-09-17
  • 2017-09-28
  • 2016-12-20
相关资源
最近更新 更多