我正在使用reactjs、nodejs和mysql数据库开发一个web应用程序。
我想通过链接(http://localhost:5000/api/v/companies) .What代码列出在浏览器中的数据库中创建的表中创建的数据,我是否应该在用reactsjs创建的页面中写入这些数据?下面是我创建的表的后端index.js文件中的代码:
const express = require("express");
const app = express();
const cors = require("cors");
const pe = require('parse-error');
const logger = require('morgan');
const database = require('./mysql');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
extended: false,
limit: '800mb'
}));
// CORS
app.options("*", cors());
app.use(cors());
database.connect(function(err) {
if (err) throw err;
console.log("==> MySQL Connected Successfully!");
// The main page
app.get('/', function (req, res) {
res.json({
version: 'v1',
status: true
});
});
const stations = require('./routes/stations');
const companies = require('./routes/companies');
app.use('/api/v1', [stations, companies]);
});
app.listen(5000, () => {
console.log("Server is running on port 5000");
});
process.on('unhandledRejection', error => {
console.error('Uncaught Error', pe(error));
});以及在后端创建的其他文件。
const database = require('./../mysql');
/**
* List all companies
*/
const getAllCompanies = async function(req, res, next) {
try {
database.query('SELECT * FROM infos_stations.Companies', function (err, result, fields) {
if (err) throw err;
return res.status(200).json(result);
});
} catch (err) {
return res.status(500).send({
code: 500,
status: false,
data: "Internal Server Error"
});
}
};
module.exports = {
getAllCompanies,
};发布于 2022-05-15 16:21:47
在reactjs应用程序中,必须安装用于请求的任何库。Axios是一个Javascript库,用于从浏览器发出来自node.js或XMLHttpRequests的HTTP请求,同时也支持ES6承诺.
app.post('/getdata‘、函数(req、res) { //数据库查询等)//发送响应(数据库结果)。}
在reactjs中,您可以通过单击按钮创建请求,也可以在组件上使用UseEffect钩子创建请求。
axios({方法:'POST',url:'htttp // localhost/getdata',responseType:'stream‘}) .then(函数(响应){// response.data拥有所有数据库数据。//将响应数据存储在任何reactjs状态。);
https://stackoverflow.com/questions/72179068
复制相似问题