javascript - 如何将 Express js 导入到 React js 中?

标签 javascript mysql node.js reactjs

是否可以将 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/

相关文章:

mysql - 如果计数为空,则应显示零值

mysql - #1064 - 您的 SQL 语法有错误......第 15 行 'TYPE=MyISAM AUTO_INCREMENT=1' 附近

javascript - 尝试添加垂直 div 和其他内容被推下

javascript - 在 ng-repeat 中使用指令

MySQL ORDER BY 返回可变长度字符串的错误结果

node.js - 使用 Angular2 的 Service Worker 推送通知

node.js - 考虑到 k8s,如何让两个后端 nodejs 服务器相互通信以处理不同的任务

javascript - jQuery 清除日期选择器字段中的值,绑定(bind)到未选中的复选框

javascript - 投资组合扩展器宽度 - Jquery CSS

node.js - 执行 Node 包命令在 Ubuntu 12.04 RTS 上不起作用