是否可以将Express js导入React js?我使用Express js与MySql进行数据库连接,MySql从表中检索行。我需要在反应应用程序中显示结果。怎么能实现呢?
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();
答案 0 :(得分:1)
节点
中有类似的东西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
});
答案 1 :(得分:0)
您只需添加以下路线即可在Express服务器上运行React应用程序:
// React
router.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '../../../dist/index.html'));
});
但是当然你应该提供自己的路径到React&#34;入口点&#34;。 在此之后,您只需使用React组件中的提取(或Redux的动作/缩减器或您喜欢的任何位置)即可轻松访问API的端点。
使用此解决方案,您无需保留2个单独的服务器(一个用于React应用程序,另一个用于您的API)