是否可以将Express js导入React js中? 我已经使用Express js与MySql进行数据库连接,该数据库从表中检索行。 我需要在react应用程序中显示结果。 如何实现?
var express = require('express');
var app = express();
var PORT = 3000;
app.listen(PORT, function(){
console.log('http://localhost:'+ PORT);
});
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'example'
});
connection.query('SELECT * from customers', function(err, rows, fields) {
if (!err)
console.log('The solution is: ', rows);
else
console.log('Error while performing Query.');
});
connection.end();
在节点这样的事情
app.get('/customers', function (req, res) {
connection.query('SELECT * from customers', function(err, rows, fields) {
if (!err)
//process your db result here and then response
res.json(result);
connection.end();
else
res.status(500).json(err);
connection.end();
});
})
在反应中,您可以使用提取模块
fetch(`http://<host>:<port>/customers`)
.then(result=> {
//here inside result you have the response from your express app
});
您只需添加以下路由,即可在Express服务器上运行React应用:
// React
router.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '../../../dist/index.html'));
});
但是,当然,您应该提供自己的到达React“入口点”的路径。 之后,您可以使用React组件中的访存(或Redux的action / reducer或任何您喜欢的地方)来简单地到达API的端点
使用此解决方案,您将无需保持2台单独的服务器(一个用于React应用程序,另一个用于API)。