Answer the question
In order to leave comments, you need to log in
How to convert the result of the selection to JSON and pass it to the client side?
On the server side (backend), using Sequelize, I connect to the Postgres database and get a selection of data from one of the tables (entities). When I try to send the result of the selection in JSON format to the client side (frontend), I get an error in the browser console:
Uncaught (in promise) TypeError: this.state.party.map is not a function
const express = require('express');
const app = express();
const Sequelize = require('sequelize');
const sequelize = new Sequelize('testdb', 'postgres', 'somePassword', {
dialect: 'postgres',
define: {
timestamps: false
}
}); // данные для подключения к бд
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database: ', err);
}); // подключение к бд
const Party = sequelize.define('party', {
name: {
type: Sequelize.STRING
}
}); // определяем модель (таблицу в бд) Party
Party.findAll().then(party => {
console.log(JSON.stringify(party));
}); // выборка данных (выводим в консоль для проверки)
app.route('/party-table')
.get((req, res) => {
res.send('get...');
})
.post((req, res) => {
console.log(req.body);
res.send(
Party.findAll().then(party => {
return JSON.stringify(party);
}) // выборка данных
);
})
.put((req, res) => {
res.send('put');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server listening on: ${PORT}`);
});
import React, { PropTypes, Component } from 'react';
class PartyTable extends Component {
constructor(props) {
super(props);
this.state = {
party: []
};
this.handleFetch = this.handleFetch.bind(this);
}
componentDidMount() {
this.handleFetch();
}
handleFetch() {
fetch('http://127.0.0.1:3000/party-table', {
method: 'POST'
})
.then((response) => {
if (response.status >= 400) {
throw new Error('Bad response from server');
}
return response.json();
})
.then(stories =>
this.setState({ party: stories }) // новое состоняние
);
}
render() {
return (
<table className='table table-striped table-hover table-bordered'>
<thead className='table__thead'>
<TableHeader/>
</thead>
<tbody>
{this.state.party.map(item => { // на эту строку ругается браузер (сообщение об ошибке в консоли)
return (<TableRow key={item.id} value={item.name}/>);
})
}
</tbody>
</table>
);
}
}
PartyTable.propTypes = propTypes;
PartyTable.defaultProps = defaultProps;
export default PartyTable;
[{"id":1,"name":"Партия1"},{"id":2,"name":"Партия2"},{"id":3,"name":"Партия3"},{"id":4,"name":"Партия4"},{"id":5,"name":"Партия5"}]
{"isFulfilled":false,"isRejected":false}
Answer the question
In order to leave comments, you need to log in
Problematic place:
res.send(
Party.findAll().then(party => {
return JSON.stringify(party);
});
);
.post(async (req, res) => {
const party = await Party.findAll();
res.json(party);
})
.post(async (req, res) => {
res.json(await Party.findAll());
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question