[英]Can't reach POST RESPONSE json - ReactJS, NodeJS
我有自己的 API 服務器,它連接到 mysql db。 當我向服務器發送請求時一切正常,我在控制台中看到來自瀏覽器的輸入和來自 db 的輸出。 但是我在瀏覽器中看不到任何新內容。 我想要更新值,但什么都沒有。 瀏覽器和服務器控制台的圖像或當我想打印狀態時,它不會得到任何更新
瀏覽器
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 in
.then(qo => this.setState({queryOutput: qo}));
IE
.then(qo => console.log(qo));
我使用await
關鍵字並輕松等待正確的輸出。 很抱歉我的初學者的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.