【发布时间】:2020-07-09 20:56:04
【问题描述】:
试图弄清楚如何从 mysql 获取数据并将其显示在 ReactJS 中。我在后端使用 NodeJS 和 express。我尝试了在 Internet 上找到的代码 sn-p,但它没有按预期工作。
这是我运行 react 应用程序时得到的结果。
TypeError: http.ServerResponse is undefined
我的 NodeJS 代码
//require mysql, http and express
//const connection = createConnection({with host, user, pass, db});
const app = express();
app.get('/posts', function(request, result){
connection.connect();
connection.query("SELECT * FROM 'some_table';", function(err, results, fields){
if(err) throw err;
result.send(results);
})
connection.end();
})
app.listen(3000);
我的反应代码
class Display extends React.Component{
constructor(props){
super(props);
this.state={ posts : [] };
fetch('http://localhost:3000/posts/')
.then(response =>{
response.json();
})
.then(posts => {
this.setState({posts})
})
.then( (err) => {
console.log(err);
})
}
render(){
return(
<div>
<ul>
{this.state.posts.map( post =>
<p>
<li>Some Text_1: {post.db_col_1}</li>
<li>Some Text_2: {post.db_col_2}</li>
<li>Some Text_3: {post.db_col_3}</li>
</p>
)}
</ul>
</div>
)
}
}
export default Display;
【问题讨论】:
-
你考虑过尝试 axios、ajax、fetch 吗?
-
也许我没听明白,但我在代码的 react 部分使用了 fetch。
-
您是否按照以下说明进行操作:w3schools.com/nodejs/nodejs_mysql.asp?
标签: mysql node.js reactjs express httpserver