【发布时间】:2019-04-09 03:10:59
【问题描述】:
我正在尝试制作一个非常基本的全栈应用程序,其中前端是 Gatsby,后端是一个简单的 Express 服务器。我有一个数据库,其中有一些用户,目标是通过查询在后端获取这些用户,然后使用 fetch() 在 Gatsby (React) 组件中显示它们。显然出了点问题,我无法在屏幕上显示它们,即使使用 Postman 请求被正确处理。 以下是相关的代码片段:
Express:我使用了经典的 express-generator,我只更改了路由文件 users.js,将其链接到数据库。 (由于 Gatsby 使用 8000 端口,因此无需更改端口,以便 React 和 express 不会重叠。
var express = require('express');
var router = express.Router();
const mysql = require('mysql');
var mysqlconnection = mysql.createConnection({
host : ****,
user : ****,
password : ****,
database : ****
});
mysqlconnection.connect(function(err) {
if (err) {
console.log(err)
}
else {
console.log(`You are now connected` )
}
})
router.get('/', (req, res) => {
mysqlconnection.query('SELECT * FROM table_basic', (err, rows, fields) => {
if(!err) {
res.send(JSON.stringify(rows, undefined, 2));
}
else {
console.log(err)
}
})
})
module.exports = router;
Gatsby 页面:这不是主要的 index.js 文件,它是页面文件夹中编码为 contacts.js 的辅助页面(Gatsby 使用内置路由方法)。该组件被包裹在布局周围(页脚和页眉,像 hbs 部分一样工作)。
import React, { Component } from 'react';
import './contacts.css';
import Layout from '../components/layout';
export default class About extends Component {
constructor(props) {
super(props)
this.state = {
users: []
}
}
componentDidMount() {
fetch('/users')
.then(res => res.json())
.then(users => this.setState({ users }));
}
render() {
return (
<Layout>
<h1>LISTING</h1>
<ul>
{this.state.users.map(user =>
<li key={user.id}>{user.lastname}</li>
)}
</ul>
</Layout>
)
}
}
最后,为了链接后端和前端,我在 Gatsby package.json 中添加了"proxy": "http://localhost:3000", 以指向 Express 服务器。那里一切正常,使用 Postman 以及我尝试获取数据的任何地方,但它们不会显示在屏幕上。有任何想法吗?
【问题讨论】:
标签: sql node.js ajax http express