TypeError:使用multer reactjs和axios无法读取未定义的属性“ path”

时间:2019-12-11 02:07:55

标签: node.js reactjs express axios multer

每当我尝试以响应方式从表单发送petImage数据时

  

TypeError:无法读取未定义的属性'path'

错误日志的第一行是

  

/mnt/c/Users/Josh/Desktop/pet_adopt_app/server/index.js:58:28

我非常确定我的错误是axios的客户端,因为我用邮递员测试了路由终点,并且可以将petImage发送到数据库。

这是代码

反应组件:

import React, { Component } from 'react';
import axios from 'axios';

export default class NewPet extends Component {
    constructor(props) {
        super(props);

        this.onChangeSpecies = this.onChangeSpecies.bind(this);
        this.onChangeName = this.onChangeName.bind(this);
        this.onChangeAge = this.onChangeAge.bind(this);
        this.onChangeImage = this.onChangeImage.bind(this);
        this.onSubmit = this.onSubmit.bind(this);

        this.state = {
            species: '',
            name: '',
            age: '',
            petImage: ''
        }
    }

    onChangeSpecies(e) {
        this.setState({
            species: e.target.value
        });
    }

    onChangeName(e) {
        this.setState({
            name: e.target.value
        });
    }

    onChangeAge(e) {
        this.setState({
            age: e.target.value
        });
    }

    onChangeImage(e) {
        this.setState({
            petImage: e.target.files[0]
        });
    }

    onSubmit(e) {
        e.preventDefault();


        const pet = {
            species: this.state.species,
            name: this.state.name,
            age: this.state.age,
            petImage: this.state.petImage
        }


        console.log(pet);

        axios.post('http://localhost:5000/add_pet', pet)
            .then(res => console.log(res.data));

        //window.location = '/';

    }

    render() {
        return (
            <div>
                <h3>Add a Pet for Adoption</h3>
                <form onSubmit={this.onSubmit} encType="multipart/form-data">
                    <div className="form-group">
                        <label>Species:</label>
                        <input
                        type="text"
                        className="form-control"
                        value={this.state.species}
                        onChange={this.onChangeSpecies}
                        />

                    </div>
                    <div className="form-group">
                      <label>Name:</label>
                      <input
                        type="text"
                        className="form-control"
                        value={this.state.name}
                        onChange={this.onChangeName}
                        />
                    </div>
                    <div className="form-group">
                        <label>Age:</label>
                        <input
                        type="text"
                        className="form-control"
                        value={this.state.age}
                        onChange={this.onChangeAge}
                        />
                    </div>
                    <div className="form-group">
                        <label>Image:</label>
                        <input
                        type='text'
                        className="form-control"
                        value={this.state.petImage}
                        onChange={this.onChangeImage}
                        />
                        <input
                        type="file"
                        className="form-control-file"
                        />
                    </div>

                    <input type="submit" value="Add New Pet" className="btn btn-primary"/>
                </form>
            </div>
        )
    }
}

Nodejs server file:

const express      = require('express');
const MongoClient  = require('mongodb').MongoClient;
const objectID     = require('mongodb').ObjectID;
const assert       = require('assert');
const bodyParser   = require('body-parser');
const cors         = require('cors');
const multer       = require('multer');
const path         = require('path');
//const uri        = require('../config/db');

const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, './uploads/');
    },
    filename: function(req, file, cb) {
        cb(null, new Date().toISOString() + file.originalname);
    }
})
const upload       = multer({storage: storage, limits: {
    fileSize: 1024 * 1024 * 5
}});

const app          = express();

const port = process.env.PORT || 5000

// Connection URL
const uri = "mongodb+srv://joshdavid86:rocafella86@cluster0-f3byx.mongodb.net/test?retryWrites=true&w=majority"

//Middleware

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');


// Database Name
const dbName = 'adopt';

// Create a new MongoClient
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

// Index route
app.get('/', function(req, res){
    res.render(__dirname + '/index.html');
  });

// Create data in database
app.post('/add_pet', upload.single('petImage'), function (req, res){
    console.log(req.file);
    const pet = {
        species: req.body.species,
        name: req.body.name,
        age: req.body.age,
        petImage: req.file.path
    };
    client.connect(err => {
        assert.equal(null, err);
        console.log("Connected successfully to server");

         const db = client.db(dbName);
            db.collection('pet').insertOne(pet).then(function(result) {

            // process result
            console.log(result,'Darcel is Beautiful and data inserted!');
            client.close();
          })
    });
    res.redirect('/');
});

// Read data from database
app.get('/pets', function(req, res){
    const resultArray = [];
    client.connect(err => {
        assert.equal(null, err);
        console.log("Connected successfully to server");
        const db = client.db(dbName);
        const cursor = db.collection('pet').find({});
    iterateFunc = (doc,err) => {
            assert.equal(null, err);
            resultArray.push(doc);
            console.log(JSON.stringify(doc, null, 4));
            if(err) {
                console.log(err)
        }
        }
            cursor.forEach(iterateFunc);
            client.close();
            res.render('index', {pets: resultArray});

      });

});  

// Update data 
app.post('/update_pet', function (req, res) {
    const pet = {
        species: req.body.species,
        name: req.body.name,
        age: req.body.age,
        petImage: req.file.path
    };
    const id = req.body.id;

    client.connect(err => {
        assert.equal(null, err);
        console.log("Connected successfully to server");
        const db = client.db(dbName);
        db.collection('pet').updateOne({"_id": objectID(id)},
        {$set: pet}, function(err, result){
            assert.equal(null, err);
            console.log('Pet updated');
            client.close();

        });
    });
});

// Delete data
app.post('/delete_pet', function (req, res) {
    const id = req.body.id;
    client.connect(err => {
      assert.equal(null, err);
      console.log("Connected successfully to server");
      const db = client.db(dbName);
      db.collection('pet').deleteOne({"_id": objectID(id)},
          function(err, result){
           assert.equal(null, err);
           console.log('Pet deleted');
           client.close();
      });
    });
});

app.listen(port, () => console.log(`Server started on port ${port} and Darcel is Beautiful`));

0 个答案:

没有答案