是否可以将 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();
最佳答案
Node 中类似的东西
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();
});
})
在 React 中你可以使用 fetch 模块
fetch(`http://<host>:<port>/customers`)
.then(result=> {
//here inside result you have the response from your express app
});
关于javascript - 如何将 Express js 导入到 React js 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44541368/