简体   繁体   English

MySQL由HTML中的node.js生成,由react.js生成

[英]MySQL result from node.js in html, by react.js

I make my first web application with nodes and reacc. 我用节点和reacc制作了第一个Web应用程序。 I do sql query in node.js and show html elements in my page. 我在node.js中执行sql查询,并在页面中显示html元素。 I need help getting the result of sql in my html page as json date. 我需要帮助来获取html页面中sql的结果作为json日期。 I put some of the code with my experiments, which may be very wrong. 我在实验中放入了一些代码,这可能是非常错误的。 Regards. 问候。

 var React = require('react'); var DefaultLayout = require('./layout/master'); var mysql = require('mysql'); var connection = mysql.createConnection({ port: '3301', host: 'localhost', user: 'root', password: 'root', database: 'nodedb', }); connection.connect(); function getArticless() { connection.query('select * from articles', function(err, result) { if (err) JSON.stringify(err); else JSON.stringify(result); }); } const jsonArticles = getArticless(); var IndexComponent = React.createClass({ render: function() { return ( <DefaultLayout name={this.props.name}> <div> {jsonArticles } </div> </DefaultLayout> ) } }); module.exports = IndexComponent; 

I am not familiar with the nuances of server side rendering with react, however there is one glaring issue that stands out with your code. 我不熟悉使用react进行服务器端渲染的细微差别,但是您的代码中存在一个明显的问题。 I do not know for sure if fixing this will make it all work, but it certainly wont work with this issue. 我不确定是否可以解决此问题,但是肯定不能解决此问题。

getArticles is a function that returns nothing and yet you call it as if it is a function that returns something. getArticles是一个不返回任何内容的函数,但是您可以像调用该函数一样返回任何内容。 Now even if you would add a return statement to this function, it will still return undefined because calls to the database happen asynchronously. 现在,即使您将return语句添加到此函数,它也将返回undefined,因为对数据库的调用是异步发生的。 This means that the function will return before the data was actually retrieved from the db. 这意味着该函数将在实际从数据库中检索数据之前返回。 This function would at the very least require a callback to be passed in, or else you can look in to the mysql-promise library and use that instead. 该函数至少需要传递一个回调,否则您可以查看mysql-promise库并使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM