2017-07-20 30 views
0

我想從我的服務器獲取數據並在reactjs中顯示它。我認爲我的錯誤是在客戶端。我從API獲取數據,我知道數據調用的工作原理,但我不是專家使用獲取,我正在學習。我無法使用reactjs和express來從我的服務器獲取數據

這是我的服務器

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; 
+0

嘗試從'componentDidMount'函數中刪除'return'語句,看看它是否有效,只需調用'fetch'而不返回它 – tibuurcio

回答

1

陣營只會渲染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元素。

+1

它的工作原理謝謝 –

相關問題