我无法使用reactjs和express从我的服务器获取数据

时间:2017-07-20 21:45:24

标签: api reactjs express fetch

我想从我的服务器获取数据并在reactjs中显示它。我认为我的错误是在客户端。我从API获取数据,我知道数据调用有效,但我不是专家使用fetch和我正在学习。

这是我的服务器

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mysql = require('mysql');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));

// connection configurations
const mc = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '12345',
    database: 'node_task_demo',
    //socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
});

// connect to database
mc.connect();

// default route
app.get('/', function (req, res) {
    return res.send({ error: true, message: 'hello' })
});

// Here where I'm calling in the client side
app.get('/todos', function (req, res) {
    mc.query('SELECT * FROM tasks', function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'Todo list' });
    });
});

// Search for todos with ‘bug’ in their name
app.get('/todos/search/:keyword', function (req, res) {
  var mensaje = 'Todos search list.';
    let keyword = req.params.keyword;
    mc.query("SELECT * FROM tasks WHERE task LIKE ? ", ['%' + keyword + '%'], function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: mensaje});
    });
});

// Retrieve todo with id
app.get('/todo/:id', function (req, res) {

    let task_id = req.params.id;

    if (!task_id) {
        return res.status(400).send({ error: true, message: 'Please provide task_id' });
    }

    mc.query('SELECT * FROM tasks where id=?', task_id, function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results[0], message: 'Todos list.' });
    });

});

// Add a new todo
app.post('/todo', function (req, res) {

    let task = req.body.task;

    if (!task) {
        return res.status(400).send({ error:true, message: 'Please provide task' });
    }

    mc.query("INSERT INTO tasks SET ? ", { task: task }, function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'New task has been created successfully.' });
    });
});

//  Update todo with id
app.put('/todo', function (req, res) {

    let task_id = req.body.task_id;
    let task = req.body.task;

    if (!task_id || !task) {
        return res.status(400).send({ error: task, message: 'Please provide task and task_id' });
    }

    mc.query("UPDATE tasks SET task = ? WHERE id = ?", [task, task_id], function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'Task has been updated successfully.' });
    });
});

//  Delete todo
app.delete('/todo', function (req, res) {

    let task_id = req.body.task_id;

    if (!task_id) {
        return res.status(400).send({ error: true, message: 'Please provide task_id' });
    }
    mc.query('DELETE FROM tasks WHERE id = ?', [task_id], function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'Task has been updated successfully.' });
    });
});

// all other requests redirect to 404
app.all("*", function (req, res, next) {
    return res.send('page not found');
    next();
});

// port must be set to 8080 because incoming http requests are routed from port 80 to port 8080
app.listen(8081, function () {
    console.log('Escuchando por el puerto 8081');
});

// allows "grunt dev" to create a development server with livereload
module.exports = app;

这是我的客户

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';


class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      data: []
    }
  }

  componentDidMount() {
    return fetch('/todos')
    .then((response) => response.json())
    .then((responseJson) =>{
      this.setState({
        data: responseJson.data
      });
    })
  }

  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro">
          Este es el resultado de la consulta = <b>{this.state.data}</b>
        </p>
      </div>
    );
  }
}

export default App;

1 个答案:

答案 0 :(得分:1)

React只会渲染JSX或字符串。除非this.state.data是一个字符串,否则您需要将其转换为React渲染。

您可以通过对数据进行字符串化来测试:

    <p className="App-intro">
      Este es el resultado de la consulta = <b>{JSON.stringify(this.state.data)}</b>
    </p>

如果this.state.data是一个数组,则需要将其映射到JSX元素。