Новичок здесь, я пытаюсь сделать POST-запрос, используя ax ios от переднего конца реагирования. Я пытался использовать express для непосредственного выполнения операций с моей базой данных postgreSQL, но это не сработало. Таким образом, я использовал ax ios для получения данных, что сработало, поэтому я надеялся, что ax ios 'POST также будет работать. Тем не менее, я получаю результат:
TypeError: Cannot destructure property `semester1` of 'undefined' or 'null'.
на локальном хосте, ошибка привела к:
500 (Internal Server Error)
Вот мой код:
import React from 'react'
import axios from 'axios'
import { Add } from '../styledComponents/scaddGrades'
const apiURL = `http://localhost:5000/grades`;
class addGrades extends React.Component {
constructor(props) {
super(props);
this.state = {
sem1: 0,
sem2: 0,
sem3: 0,
sem4: 0,
final: 0,
}
this.onButtonClick = this.onButtonClick.bind(this);
this.inputHandler = this.inputHandler.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
onButtonClick(e) {
e.preventDefault();
console.log("Add Grades")
}
handleSubmit(e) {
e.preventDefault();
const data = {
semester1: this.state.sem1,
semester2: this.state.sem2,
semester3: this.state.sem3,
semester4: this.state.sem4,
finalgrades: this.state.final
}
axios.post(apiURL, { data })
.then(res => {
console.log("response: ", res)
})
.catch(error => {
console.log(error)
})
}
inputHandler(e) {
this.setState({
[e.target.name]: e.target.value
})
console.log(this.state)
}
render() {
return (
<div>
<Add id="AddGrades" onClick={this.onButtonClick}>Add Grades</Add>
<form onSubmit={this.handleSubmit}>
<input type="text" name="sem1" onChange={this.inputHandler} />
<input type="text" name="sem2" onChange={this.inputHandler} />
<input type="text" name="sem3" onChange={this.inputHandler} />
<input type="text" name="sem4" onChange={this.inputHandler} />
<input type="text" name="final" onChange={this.inputHandler} />
<button type="submit"> Add</button>
</form>
</div>
)
}
}
export default addGrades;
Редактировать : Вот мой код для API (используя express)
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const { pool } = require('./config')
const PORT = process.env.PORT || 5000;
const app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(cors())
const getGrades = (request, response) => {
pool.query('SELECT * FROM grades', (error, results) => {
if (error) {
throw error
}
response.status(200).json(results.rows)
response.end(JSON.stringify(results))
})
}
const addGradesToDatabase = (request, response) => {
const { semester1, semester2, semester3, semester4, finalgrades } = request.bodyParser
pool.query('INSERT INTO grades (semester1, semester2, semester3, semester4, finalgrades) VALUES($1, $2, $3, $4, $5)', [semester1, semester2, semester3, semester4, finalgrades], error => {
if (error) {
throw error
}
response.status(201).json({ status: 'success', message: 'Grades added' })
})
}
const updateGrades = (request, response) => {
const id = parseInt(request.params.id)
const { semester1, semester2, semester3, semester4, finalgrades } = request.bodyParser
pool.query('UPDATE grades SET semester1 = $1, semester2 = $2, semester3 = $3, semester4 = $4, semester5 = $5 WHERE id = $7',
[semester1, semester2, semester3, semester4, finalgrades, id], (error, results) => {
if (error) {
throw error
}
response.status(200).send(`grades modified with ID: ${id}`)
})
}
const deleteGrades = (request, response) => {
const id = parseInt(request.params.id)
pool.query('DELETE FROM grades WHERE id = $1', [id], (error, results) => {
if (error) {
throw error
}
response.status(200).send(`grades modified with ID: ${id}`)
})
}
app
.route('/grades')
.get(getGrades)
.post(addGradesToDatabase)
.put(updateGrades)
.delete(deleteGrades)
module.exports = {
getGrades,
addGradesToDatabase,
updateGrades,
deleteGrades,
}
//Start Server
app.listen(PORT, () => {
console.log(`Server listening at port: ${PORT}`)
})