使用React显示REST API响应

时间:2017-04-03 23:13:52

标签: rest api reactjs

我目前正在尝试创建一个新的网络应用。

作为其中的一部分,我创建了一个REST API,如下面的sevrer.js文件中所示......

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());

var mysql = require('mysql');
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    database: 'database'
});

connection.connect(function(err) {
    if(err) {
        console.log(err);
        process.exit(1);
    }

    db = connection;
    console.log('Database connection ready');

    var server = app.listen(process.env.PORT || 8080, function(){
        var port = server.address().port;
        console.log("App now running on port", port);
    });
});


// Generic error handler used by all endpoints.
function handleError(res, reason, message, code) {
    console.log("ERROR: " + reason);
    res.status(code || 500).json({"error": message});
}

app.get("/api/deals", function(req, res) {
    connection.query('SELECT * FROM TEMPDATA LIMIT 5',[1, 2], function(err, docs) {
        if(err) {
            handleError(res, err.message, "Failed to get deals");
        } else {
            res.status(200).json(docs);
        }
    })
});

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// define the folder that will be used for static assets
app.use(Express.static(path.join(__dirname, 'static')));

app.get('/', (req, res) => {
    match(
        { routes, location: req.url },
        (err, redirectLocation, renderProps) => {

            // in case of error display the error message
            if (err) {
                return res.status(500).send(err.message);
            }

            // in case of redirect propagate the redirect to the browser
            if (redirectLocation) {
                return res.redirect(302, redirectLocation.pathname + redirectLocation.search);
            }

            // generate the React markup for the current route
            let markup;
            if (renderProps) {
                // if the current route matched we have renderProps
                markup = renderToString(<RouterContext {...renderProps}/>);
            } else {
                // otherwise we can render a 404 page
                markup = renderToString(<NotFoundPage/>);
                res.status(404);
            }

            // render the index template with the embedded React markup
            return res.render('index', { markup });
        }
    );
});

然后我有一个反应组件,我用来尝试从数据库调用中呈现结果,如下所示......

    import React, { Component } from 'react';


export default class Layout extends Component {
    constructor() {
        super();
        this.state = { items: [] }
    }

    componentDidMount() {
        fetch(`http://localhost:8080/api/deals/`)
            .then(result=>result.json())
            .then(items=>this.setState({items}))
    }

    render() {
        return (
            <div className="app-container">
                <div className="app-content">{this.props.children}</div>
                <ul>
                    {this.state.items.map(item=><li key={item['Offer.ID']}>{item['Offer.ID']}</li>)}
                </ul>
            </div>
        );
    }
}

我可以使用http://localhost:8080/api/deals/访问api并查看所有相关数据,但是当我在浏览器上查看页面时,数据不会按预期呈现在列表中。谁能帮我理解为什么?

0 个答案:

没有答案