>  기사  >  웹 프론트엔드  >  React Native는 Fetch 메소드를 사용하여 POST 요청을 보냅니다.

React Native는 Fetch 메소드를 사용하여 POST 요청을 보냅니다.

小云云
小云云원래의
2018-01-18 14:55:105767검색

이 글에서는 Fetch 메소드를 사용하여 도메인 간 POST 요청을 보내는 React Native의 자세한 설명을 주로 소개합니다. 편집자는 꽤 좋다고 생각하므로 지금 공유하고 참고용으로 제공하겠습니다. 편집자를 따라 살펴보겠습니다. 모두에게 도움이 되기를 바랍니다.

Fetch는 미래의 트렌드가 될 것이며 필연적으로 기존 Ajax를 대체할 것이며 RN 프레임워크는 Fetch를 지원합니다. 다음은 교차 도메인 요청의 예일 뿐입니다. 이 도메인의 요청은 동일하고 더 간단합니다. 클라이언트 환경은 RN이 작성한 페이지를 사용하며, 브라우저 콘솔을 사용하여 시뮬레이션할 수도 있습니다. 백엔드 서비스는 NodeJs Express 프레임워크를 사용합니다.

1) 요청 가져오기


//发送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. 모드 속성은 도메인 간 허용 여부를 제어합니다. Same-origin(동일 출처 요청), no-cors(기본값) 및 cros(교차 도메인 요청 허용) 첫 번째 유형의 교차 도메인 요청은 오류를 보고하고 두 번째 유형은 스크립트, 사진 및 그러나 액세스되는 서비스가 도메인 간 액세스를 허용하는 경우 세 번째 방법은 타사 데이터에 액세스할 수 없습니다. 그렇지 않으면 다음 오류가 발생합니다.

2. Fetch가 배경을 요청하면 Promise 개체가 반환됩니다. 반환된 데이터를 구문 분석하기 위해 객체가 지원하는 메서드는 arrayBuffer(), blob(), formData(), json() 및 text()입니다.

3. Body가 매개변수를 전달하므로 주의하세요! 알아채다! 알아채다! 중요한 사항은 세 번만 전달할 수 있습니다. 이 매개변수 형식에서는 {a:1,b:2,...} 객체를 전달할 수 없습니다. JSON.stringify({a: 1, b:2,...})도 작동하지 않습니다. jquery에서는 들어오는 객체 프레임이 자동으로 formData로 캡슐화됩니다. Fetch에는 이 기능이 없습니다.

4. 브라우저 버전에 주의하여 사용하세요. 하위 버전에서는 이 개체를 지원하지 않습니다. RN을 사용할 수 있습니다

2) Nodejs 익스프레스 프레임워크는 도메인 간 요청을 활성화합니다.


//设置跨域访问 
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 익스프레스 프레임워크는 POST 데이터 처리 기능을 활성화합니다. 기본적으로 POST 요청의 매개변수는 요청 본문, res를 사용합니다. 쿼리는 얻을 수 없으며 res.body를 사용하여 얻어야 합니다. 전제는 본문 구문 분석 기능이 Express 프레임워크에서 활성화되어야 한다는 것입니다. 그렇지 않으면 정의되지 않음이 표시됩니다.


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 요청은 콜백으로 래핑된 데이터를 반환해야 하기 때문에 그렇지 않으면 구문 분석 오류가 발생합니다. 여기에는 $.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 front end


 /**
 * 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: &#39;center&#39;,
  alignItems: &#39;center&#39;,
  backgroundColor: &#39;#F5FCFF&#39;,
 },
 wrapper: {
  borderRadius: 5,
  marginBottom: 5,
 },
 button: {
  backgroundColor: &#39;#eeeeee&#39;,
  padding: 10,
 },
});

AppRegistry.registerComponent(&#39;HelloWorld&#39;, () => HelloWorld);

2, NodeJs


 /**
 * Created by linyufeng on 2016/8/22.
 */

var express = require(&#39;express&#39;);
//Post方式请求参数放在请求体里面,需引用body-parser解析body
var bodyParser = require("body-parser");
var app = express();

// 引用
app.use(bodyParser.urlencoded({ extended: false }));

//设置跨域访问
app.all(&#39;*&#39;, 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",&#39; 3.2.1&#39;);
 res.header("Content-Type", "application/json;charset=utf-8");
 next();
});

//json数据
var data = { "name": "Test", "age": "19" };

app.get(&#39;/&#39;, function(req, res) {
 console.log(&#39;get..........&#39;);
 console.log(req.query);
 if (req.query && req.query.callback) {
  var str = req.query.callback + "(" + JSON.stringify(data) + ")"; //jsonp 
  console.log(&#39;jsonp: &#39;+str);
  res.end(str);
 }else{
  console.log(&#39;json: &#39;+JSON.stringify(data));
  res.end(JSON.stringify(data));
 }
});

app.post(&#39;/&#39;, function(req, res) {
 console.log(&#39;post............&#39;);
 console.log(req.body);
 console.log(&#39;json: &#39;+JSON.stringify(data));
 res.end(JSON.stringify(data));
});

app.listen(8085, function () {
 console.log(&#39;Listening on port 8085...&#39;);
});

관련 권장 사항:

Ajax 포스트 요청 점프에 대한 예제 토크 솔루션 page

vue 리소스 게시 요청 중에 발생한 문제에 대한 솔루션

php에서 컬 가져오기 요청 구문 분석

위 내용은 React Native는 Fetch 메소드를 사용하여 POST 요청을 보냅니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.