无法达到 POST RESPONSE json - ReactJS, NodeJS



我有自己的API服务器,它连接到mysql数据库。当我向服务器发送请求时,一切正常,我在控制台中看到来自浏览器的输入和来自数据库的输出。但我在浏览器中看不到任何新内容。我想要更新值,但什么都不想要。浏览器和服务器控制台的图像,或者当我想打印状态时,它不会得到任何更新

浏览器

import React, {Component} from 'react';
import './data_table.css';
class DataTable extends Component {
constructor (props) {
super(props);
this.keys = [];
this.state = {
rows: {},
queryOutput: [],
}
}
componentDidMount(){
//Fetching number of affected and changed rows
fetch('/api/update')
.then(res => res.json())
.then(rows => {this.setState({rows: rows})
console.log(rows)});
//Fetching output from user query
fetch('/api/query',
{
method: "POST",
headers: {
'Content-Type': 'application/json'
},
})
.then(res => res.json())
.then(qo =>{ this.setState({queryOutput: qo})
console.log(qo)});
}
getReadyTable(){
let objectToPrint;
if(this.state.queryOutput[0]) {
objectToPrint = this.state.queryOutput;
this.keys = Object.keys(objectToPrint[0]);
return (
<table className={'output'}>
<thead>
<tr>{this.keys.map((key, val) => <th key={val}>{key}</th>)}</tr>
</thead>
<tbody>
{objectToPrint.map((obj, val) => <tr key={val}>{this.keys.map((key, idx) => <td
key={idx}>{obj[key]}</td>)}</tr>)}
</tbody>
</table>
);
}
else{
objectToPrint = this.state.rows;
this.keys = Object.keys(objectToPrint);
return (
<table className={'output'}>
<thead ><tr >{this.keys.map( (key, val) =>  <th key={val}>{key}</th> )}</tr></thead>
<tbody><tr >{Object.values(objectToPrint).map( (obj, val) => <td key={val}>{obj}</td>)}</tr></tbody>
</table>
);
}
}
render() {
return (
<div>
{this.getReadyTable()}
</div>
);
}
}
export default DataTable;

服务器

//Some requires and uses...
app.post('/api/query', (req, res) => {
console.log(`n  Query input : ${JSON.stringify(req.body)}`);
let queryInput = (Object.values(req.body).join(' '));
if(queryInput.length>4){//provisional condition
res.json(dbApi.queryFromUser(queryInput));
}
else{
res.json(dbApi.queryOutput);
}
});

MySQL连接

//Connection and others...
const receivingQuery =(queryInput) => {
db.query(queryInput, (err, result) =>{
if(err) throw err+' : '+queryInput;
queryOutput = result;
console.log("nQuery output "+ JSON.stringify(queryOutput));
});
return queryOutput;
}
module.exports={ queryFromUser: receivingQuery }

检查"this.setState({rows}("。这是不对的。你指的是哪个州?

要进行调试,请在中执行console.log

.then(qo => this.setState({queryOutput: qo}));

.then(qo => console.log(qo));

我使用await关键字,可以轻松地等待正确的输出。抱歉我的工程师出了问题。

最新更新