美文网首页
React Native用fetch调用.net mvc web

React Native用fetch调用.net mvc web

作者: Jason_兵哥 | 来源:发表于2018-06-30 00:18 被阅读40次

    用到知识:

    1. fetch的get,post

    2. .net服务端api的跨域问题

    3. 本地.net的服务端调试问题

    注意问题:

    1. 调用service时this的作用域问题

    2. .net实现api的跨域允许, 在web.config进行如下配置:

    con

    3. 直接使用vs调试模式下,使用地址localhost或者127.0.0.1发现react native无法调用,显示

    Network request faild。

    解决办法:配置服务系统到 IIS, 绑定其IP地址, 需要调试时,把VS附加到IIS进程 w3wp.exe.


    4. Asp.net服务端所有的api应该有返回值,不然在response.json()会报错, 要么服务端必须有返回值,要么前端换方式

    具体实现:

    1. 新建配置文件js用来存放api主域名地址如:

    export const apiStr = 'https://facebook.github.io/';

    2. 新建代码文件IndexPageService.js用来存放调用api的代码

    a. fetch调用json文件示例代码:

    export function getMovies(callBack) {

        fetch(apiStr + `react-native/movies.json`)

            .then((response) => response.json())

            .then((responseJson) => {

                callBack(responseJson);

            })

            .catch((error) => {

                console.error(error);

            });

    }

    调用示例:需要注意this作用域

    var _self = this;

            getMovies((d) => {

                _self.setState({

                    dataSource: d.movies

                });

            });

    b. fetch调用api的get示例

    //get example

    export function getExample(callBack) {

        fetch("http://192.168.31.41:8080/API/CRMTest/GET", {

            method: "GET"

        }).then((response) => response.json())

            .then((responseJson) => {

                callBack(responseJson);

            })

            .catch((error) => {

                console.error(error);

            });

    }

    c. fetch调用api的post方式

    //post example

    export function postExample() {

        var testModel = {

            Id: 1,

            Name: 'name'

        };

        fetch("http://192.168.31.41:8080/API/CRMTest/SaveData", {

            method: "POST",

            headers: {

                "Accept": "application/json",

                'Content-Type': 'application/json',

            },

            body: JSON.stringify(testModel)

        }).then((response) =>

            response.json()

        ).then((responseJson) => {

            alert(responseJson);

        })

            .catch((error) => {

                console.error(error);

            });

    }

    Asp.net建WebApi简约示例项目步骤

    相关文章

      网友评论

          本文标题:React Native用fetch调用.net mvc web

          本文链接:https://www.haomeiwen.com/subject/wuyzyftx.html