用到知識:
1.?fetch的get,post
2. .net服務端api的跨域問題
3.?本地.net的服務端調試問題
注意問題:
1. 調用service時this的作用域問題
2. .net實現(xiàn)api的跨域允許,?在web.config進行如下配置:
3.?直接使用vs調試模式下凌埂,使用地址localhost或者127.0.0.1發(fā)現(xiàn)react native無法調用集漾,顯示
Network request faild。
解決辦法:配置服務系統(tǒng)到 IIS,?綁定其IP地址,?需要調試時,把VS附加到IIS進程?w3wp.exe.
4. Asp.net服務端所有的api應該有返回值租副,不然在response.json()會報錯,?要么服務端必須有返回值,要么前端換方式
具體實現(xiàn):
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);
? ? ? ? });
}