从数据库渲染数据

时间:2017-04-20 04:26:11

标签: mysql node.js react-native fetch-api

我正在使用react native来构建应用程序。使用node js,express和mysql作为后端。 插入数据似乎工作正常。但我无法从表中检索数据。这是我试过的fetch API,但我不确定它是否正确。我是React Native的新手。

import React,{Component} from 'react';
import {
Text,
View
}from 'react-native';

export default class UserProfile extends Component{

constructor(props){
super(props);
this.state={name:''}
};

componentWillMount(){
    return this.getUser();
}

getUser(){
    return fetch('http://192.168.0.20:3000/users',{
    method:'GET',
    headers:{
            'Accept':'application/json',
            'Content-Type':'application/json',
        }
    })
    .then((response)=>response.json())
    .then((response) => this.setState({
    name: response.name})
    )
}


render(){
    return(
        <View style={{marginTop:100}}>
             <Text>UserName:{this.state.name}</Text>
        </View>

   );
 }
}

后端代码:

var express = require('express');
var router = express.Router();
var mysql =  require('mysql');

var connection = mysql.createConnection({
      host: 'localhost',
      user: 'root',`enter code here`
      password: '',
      database:'backend',
})

/* our backend endpoint to check for users in the database */
router.post('/', function(req, res, next) {

        var name=req.body.name;
        var phone=req.body.phone;
        var email = req.body.email;
        var password = req.body.password;

        connection.query("SELECT * FROM user WHERE email =? ",[email],function(err,row,fields){
          console.log(name);
          if (err) console.log(err);
  });
  });

module.exports = router;

0 个答案:

没有答案