8
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ReactNativeでPOSTする

Last updated at Posted at 2018-11-03

特に何だということはないですが、簡単なPOSTのサンプル。

API側(PHP)

<?php

    $email = $_POST['email'];
    $password = $_POST['password'];

    $res = [];

    if($email == 'test@test.com' && $password == 'test'){
        $res['status'] = 'OK';
        $res['auth'] = true;
    }else{
        $res['status'] = 'OK';
        $res['auth'] = false;
    }

    header('Content-type: application/json');
    echo json_encode($res);

ReactNative側

追加モジュールインストール

npm install --save react-native-elements
npm install --save axios
npm install

App.js

App.js
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { Card, Button, FormLabel, FormInput } from "react-native-elements";
import axios from 'axios';

export default class App extends React.Component {

  state = {
    email : 'test@test.com',
    password: 'test'
  }

  authPost = () => {

    //受け取り側が素のPHP($_POST['']なのでstringifyする)
    //Laravelとかならいらない
    var qs = require('qs');

    axios
      .post('http://localhost/auth/api.php', qs.stringify({email: this.state.email, password: this.state.password}))
      .then((res) => {
        if(res.data.auth){
          alert('認証OK');
        }else{
          alert('認証NG');
        }
      })
      .catch(error => console.log(error));
  }

  render() {
    return (
      <View style={{paddingVertical:20}}>
        <Card>
          <FormLabel>Email</FormLabel>
          <FormInput
            autoCapitalize='none'
            value={this.state.email}
            onChangeText={text => this.setState({email:text})}
          />
          <FormLabel>Password</FormLabel>
          <FormInput
            secureTextEntry
            value={this.state.password}
            onChangeText={text => this.setState({password:text})}
          />
          <Button
            title='送信'
            buttonStyle={{marginTop:20}}
            borderRadius={10}
            onPress={() => this.authPost(this.state.email, this.state.password)}
          />
        </Card>
      </View>
    );
  }
}

8
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?