Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Api 我无法使用reactjs和express从服务器获取数据_Api_Reactjs_Express_Fetch - Fatal编程技术网

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

Api 我无法使用reactjs和express从服务器获取数据,api,reactjs,express,fetch,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()

我想从我的服务器获取数据,并在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;

React将仅呈现JSX或字符串。除非this.state.data是一个字符串,否则您需要将其转换为其他字符串

您可以通过字符串化数据来测试这一点:

    <p className="App-intro">
      Este es el resultado de la consulta = <b>{JSON.stringify(this.state.data)}</b>
    </p>
如果this.state.data是一个数组,则需要将其映射到JSX元素。

尝试从componentDidMount函数中删除return语句,看看它是否有效,只需调用fetch而不返回它