国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

詳解React Native 采用Fetch方式發送跨域POST請求

2019-11-19 14:55:53
字體:
來源:轉載
供稿:網友

Fetch以后是趨勢,勢必要取代傳統的Ajax,而且RN框架支持Fetch。下面僅做了一個跨域請求的例子,在本域請求是一樣的,而且更簡單一些。客戶端環境用的是RN寫的一個頁面,也可以用瀏覽器的console控制臺模擬。后端服務用的是NodeJs express框架。

1)Fetch請求

//發送Ajax請求  sendAjax(){   //POST方式,IP為本機IP   fetch("http://192.168.111.102:8085", {    method: "POST",    mode: "cors",    headers: {     "Content-Type": "application/x-www-form-urlencoded"    },    body: 'key=1'   }).then(function (res) {    console.log("fetch request ", JSON.stringify(res.ok));    if(res.ok){     res.json().then(function (json) {      console.info(json);      Alert.alert('提示','來自后臺數據:名字'+json.name+'、年齡'+json.age,[{text: '確定', onPress: () => console.log('OK Pressed!')},]);     });    }else{     Alert.alert('提示','請求失敗',[{text: '確定', onPress: () => console.log('OK Pressed!')},]);    }    }).catch(function (e) {    console.log("fetch fail");    Alert.alert('提示','系統錯誤',[{text: '確定', onPress: () => console.log('OK Pressed!')},]);   });  } 

1、mode屬性控制是否允許跨域。same-origin(同源請求)、no-cors(默認)和cros(允許跨域請求),第一種跨域求情會報error,第二種可以請求其他域的腳本、圖片和其他資源,但是不能訪問response里面的屬性,第三種可以獲取第三方數據,前提是所訪問的服務允許跨域訪問。否則,會出現如下錯誤:

2、Fetch請求后臺時,返回時一個Promise對象。對象支持解析返回數據的方法有:arrayBuffer()、blob()、formData()、json()、text()。

3、Body傳入參數,注意!注意!注意!重要的事情說三次,只能傳啊a=1&b=2...這種參數形式,不可傳對象{a:1,b:2,...},用JSON.stringify({a:1,b:2,...})也不行。在jquery中,傳入對象框架會自動封裝成formData的形式,fetch沒有這個功能。

4、使用時請注意瀏覽器版本,低版本不支持此對象。RN是可以用的

2)Nodejs express框架開啟允許跨域請求:

//設置跨域訪問 app.all('*', function(req, res, next) {  res.header("Access-Control-Allow-Origin", "*");  res.header("Access-Control-Allow-Headers", "X-Requested-With");  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");  res.header("X-Powered-By",' 3.2.1');  res.header("Content-Type", "application/json;charset=utf-8");  next(); }); 

3)Nodejs express框架開啟處理POST數據功能,默認POST請求的參數是在請求體里面,用res.query是獲取不到的,為{};需要使用res.body獲取,前提是要在express框架里面開啟body解析功能,否則顯示undefined。

var express = require('express'); //Post方式請求參數放在請求體里面,需引用body-parser解析body var bodyParser = require("body-parser"); var app = express();  // 引用 app.use(bodyParser.urlencoded({ extended: false })); 

4)支持jsonp方式跨域訪問,開啟跨域訪問后用傳統的jsonp方式請求時,會報錯。因為jsonp請求需要返回一個callback包裹的數據,否則解析出錯。此處有一個坑,用$.ajax({method:'POST',dataType:'jsonp'})方式請求時,依然發送的是GET請求。

//json數據 var data = { "name": "Test", "age": "19" };  app.get('/', function(req, res) {  console.log('get..........');  console.log(req.query);  if (req.query && req.query.callback) {   var str = req.query.callback + "(" + JSON.stringify(data) + ")"; //jsonp   console.log('jsonp: '+str);   res.end(str);  }else{   console.log('json: '+JSON.stringify(data));   res.end(JSON.stringify(data));  } }); 

5)完整代碼:

1、RN前端

 /** * Created by linyufeng on 2016/8/22. */import React, { Component } from 'react';import { AppRegistry, StyleSheet, Text, TouchableHighlight, Alert, View} from 'react-native';class HelloWorld extends Component {//發送Ajax請求 sendAjax(){  //POST方式  fetch("http://192.168.111.102:8085", {   method: "POST",   mode: "cors",   headers: {    "Content-Type": "application/x-www-form-urlencoded"   },   body: 'key=1'  }).then(function (res) {   console.log("fetch request ", JSON.stringify(res.ok));   if(res.ok){    res.json().then(function (json) {     console.info(json);     Alert.alert('提示','來自后臺數據:名字'+json.name+'、年齡'+json.age,[{text: '確定', onPress: () => console.log('OK Pressed!')},]);    });   }else{    Alert.alert('提示','請求失敗',[{text: '確定', onPress: () => console.log('OK Pressed!')},]);   }  }).catch(function (e) {   console.log("fetch fail");   Alert.alert('提示','系統錯誤',[{text: '確定', onPress: () => console.log('OK Pressed!')},]);  }); } render() {  return (   <View style={styles.container}>    <TouchableHighlight style={styles.wrapper}     onPress={this.sendAjax}>     <View style={styles.button}>      <Text>點擊發送Ajax請求</Text>     </View>    </TouchableHighlight>   </View>  ); }}const styles = StyleSheet.create({ container: {  flex: 1,  justifyContent: 'center',  alignItems: 'center',  backgroundColor: '#F5FCFF', }, wrapper: {  borderRadius: 5,  marginBottom: 5, }, button: {  backgroundColor: '#eeeeee',  padding: 10, },});AppRegistry.registerComponent('HelloWorld', () => HelloWorld);

2、NodeJs

 /** * Created by linyufeng on 2016/8/22. */var express = require('express');//Post方式請求參數放在請求體里面,需引用body-parser解析bodyvar bodyParser = require("body-parser");var app = express();// 引用app.use(bodyParser.urlencoded({ extended: false }));//設置跨域訪問app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); res.header("X-Powered-By",' 3.2.1'); res.header("Content-Type", "application/json;charset=utf-8"); next();});//json數據var data = { "name": "Test", "age": "19" };app.get('/', function(req, res) { console.log('get..........'); console.log(req.query); if (req.query && req.query.callback) {  var str = req.query.callback + "(" + JSON.stringify(data) + ")"; //jsonp   console.log('jsonp: '+str);  res.end(str); }else{  console.log('json: '+JSON.stringify(data));  res.end(JSON.stringify(data)); }});app.post('/', function(req, res) { console.log('post............'); console.log(req.body); console.log('json: '+JSON.stringify(data)); res.end(JSON.stringify(data));});app.listen(8085, function () { console.log('Listening on port 8085...');});

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 夏邑县| 方山县| 五台县| 卫辉市| 突泉县| 年辖:市辖区| 乡宁县| 乐昌市| 同德县| 伊吾县| 林周县| 绵阳市| 夏河县| 岳普湖县| 尼勒克县| 宜兰市| 马山县| 衡水市| 神木县| 双柏县| 巴马| 临湘市| 丰顺县| 罗源县| 慈溪市| 定安县| 紫云| 昌乐县| 海阳市| 虞城县| 东至县| 涞水县| 秀山| 甘孜县| 潢川县| 明溪县| 浮梁县| 大邑县| 定陶县| 江门市| 东台市|