Я создаю простое приложение MERN, в моем бэкэнде я использую REST-клиент, чтобы проверить, отправляются ли данные в базу данных, и он работает нормально, но в моем интерфейсе отправка обработки формы в базу данных не работает, отправленные данные являются объектом продукта с именем, изображением, ценой и доступными атрибутами
backend:
server. js
const express = require('express')
const app = express()
const mongoose = require('mongoose')
const dotenv = require('dotenv')
const userURLS = require('./api/auth')
const multer = require('multer')
const productsURLS = require('./api/products')
dotenv.config()
mongoose.connect(process.env.DB_ACCESS, { useNewUrlParser: true }, () => {
console.log('DB CONNECTED!')
})
app.use(express.json())
app.use('/user', userURLS)
app.use(multer({ dest: "./uploads/" ,
rename: (fieldname, filename) => {
return filename;
}
}).single('photo'));
app.use('/products', productsURLS)
app.listen(7000, ()=> {
console.log('Server is Up & Running!')
})
product. js
const express = require('express')
const router = express.Router()
const fs = require('fs')
const product = require('../models/products');
const { request } = require('http');
const { response } = require('express');
router.post('/add-product', (request,response) => {
var newItem = new product({
name:request.body.name,
img:request.body.img,
price:request.body.price,
available:request.body.available
});
newItem.img.data = fs.readFileSync(request.body.img)
newItem.img.contentType = 'image/png';
newItem.save()
.then((data)=>{
response.json(data)
})
.catch((error)=> {
response.json(error)
})
});
router.get('/', (request, response) => {
product.find()
.then((data)=>{
response.json(data)
})
.catch((error)=> {
response.json(error)
})
})
файл test.http, используемый клиентом Rest
POST http://localhost:7000/products/add-product http/1.1
Content-Type: application/json
{
"name":"dji drone",
"img":"./uploads/dose-media-r6WkZ0gcDa0-unsplash-removebg-preview.png",
"price":"300",
"available":true
}
интерфейс:
AddProduct.jsx
import React, { Component } from 'react'
import axios from 'axios'
class AddProduct extends Component {
constructor(){
super()
this.state = {
//products:[],
name:'',
img:'',
price:'',
available:''
}
this.changedProductname = this.changedProductname.bind(this)
this.changedProductimg = this.changedProductimg.bind(this)
this.changedProductprice = this.changedProductprice.bind(this)
this.changedProductavail = this.changedProductavail.bind(this)
this.onSubmit = this.onSubmit.bind(this)
}
/*
componentDidMount(){
axios.get('http://localhost:7000/products')
.then(response =>{
if (response.data.length > 0) {
this.setState({
products:response.data.map(product => product.name),
name: response.data[0].name
})
}
})
}
*/
changedProductname(event){
this.setState({
name:event.target.value
})
}
changedProductimg(event){
this.setState({
img:event.target.value
})
}
changedProductprice(event){
this.setState({
price:event.target.value
})
}
changedProductavail(event){
this.setState({
available:event.target.value
})
}
onSubmit(event){
event.preventDefault()
const product = {
name: this.state.name,
img: this.state.img,
price: this.state.price,
available: this.state.available
}
console.log(product)
axios.post('http://localhost:7000/products/add-product', product)
.then(response => console.log(response.data))
window.location = '/'
alert("product added successfully")
}
render() {
return (
<div>
<div className="skewed"></div>
<div className='container' style={{ paddingLeft:'300px', marginTop:'160px', marginBottom:'160px' }}>
<div className="card shadow " style={{ width:'520px', height:'600px' , borderRadius:'15px' , border:'none'}}>
<form onSubmit={this.onSubmit} method="post" style={{ width:'380px', textAlign:'', marginLeft:'70px', paddingTop:'90px'}}>
<h3 style={{ paddingBottom:'30px' }}>Add product</h3>
<div className="form-group">
<label htmlFor="name">Name</label>
<input onChange={ this.changedProductname } value={ this.state.name } type="text" className="form-control" id='name'/>
</div>
<div className="form-group">
<label htmlFor="img">Image</label>
<input name='photo' onChange={ this.changedProductimg } value={ this.state.img } type="file" class="form-control-file" id='img'/>
</div>
<div className="form-group">
<label htmlFor="price">Price</label>
<input onChange={ this.changedProductprice } value={ this.state.price } type="text" className="form-control" id='price'/>
</div>
<div className="form-group form-check">
<input onChange={ this.changedProductavail } value={ this.state.available } type="checkbox" class="form-check-input" id="avail"/>
<label class="form-check-label" htmlFor="avail">Available</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
);
}
}
export default AddProduct;