反应中的axios与API抛出“网络错误”异常

时间:2017-08-08 12:55:22

标签: json api reactjs react-redux axios

我使用C#(visual studio)开发了一个API,当我发送使用浏览器或Postman获取数据的请求时,它成功返回数据, 在另一方面,我开发了一个反应应用程序,通过将请求发送到我的本地API服务来执行CRUD进程, (调试模式下的visual studio和visual studio代码) 当我使用react(axios)应用程序发送请求时,api服务获取请求,但Get函数中的axios会抛出网络错误异常,

我在谷歌尝试了很多解决方案,但没有结果。

当我使用其他API(http://jsonplaceholder.typicode.com/posts/)时,它可以正常工作 但当我使用本地api(我的api)抛出网络错误

我的反应代码:

 import axios from 'axios';
class Faq extends Component {
componentDidMount() {

        axios.get('http://localhost:53419/api/faqs')
            .then(
            response => {
                const faqs = response.data;
                this.setState(this.state.faqs = { faqs });
            }
            )
        .catch(function (error) {
                console.log(error);
            });
    }
}

我的API服务(控制器)代码:

    public class FAQsController : ApiController
    {
[ResponseType(typeof(FAQs))]
        public List<FAQs> GetFAQs()
        {
            return db.FAQs.ToList();
        }
}

我将用于将数据转换为JSON的WebAPIConfig.cs文件是:

public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes

        var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
        config.Formatters.Remove(config.Formatters.XmlFormatter);
        json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        ((DefaultContractResolver)config.Formatters.JsonFormatter.SerializerSettings.ContractResolver).IgnoreSerializableAttribute = true;

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

    }

React package.json配置:

{
  "name": "compare-react",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^0.16.2",
    "bulma": "^0.5.0",
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "react-scripts": "1.0.10",
    "whatwg-fetch": "^2.0.3"
  },
  "scripts": {
    "build-css": "node-sass-chokidar src/ -o src/",
    "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive",
    "start-js": "react-scripts start",
    "start": "npm-run-all -p watch-css start-js",
    "build": "npm run build-css && react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },

  "devDependencies": {
    "moxios": "^0.4.0",
    "node-sass-chokidar": "0.0.3",
    "npm-run-all": "^4.0.2",
    "webpack": "^3.4.1"
  }
}

0 个答案:

没有答案