Реагировать + Nodejs публикация на s3 AWS: 500 (Внутренняя ошибка сервера) - PullRequest
0 голосов
/ 03 апреля 2020

Back и Front работают, но я получаю эту ошибку, когда отправляю в корзину s3 aws:


[1] Proxy error: Could not proxy request /api/profile/profile-img-upload from localhost:3000 to http://localhost:5000.
[1] See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED).

Устранение неполадок:

  • Front и Back работают
  • Я создал aws корзину и у меня есть права администратора.
  • Я не получаю никаких ошибок спереди, ошибка 500 появляется после отправки моего файла в amazon.

Вот мои файлы:

сервер. js

const express = require( 'express' );
const bodyParser = require( 'body-parser' );
const path = require( 'path' );

const router = express.Router();

const app = express();

/**
 * Configure the middleware.
 * bodyParser.json() returns a function that is passed as a param to app.use() as middleware
 * With the help of this method, we can now send JSON to our express application.
 */
app.use( bodyParser.urlencoded( { extended: false } ) );
app.use( bodyParser.json() );

// We export the router so that the server.js file can pick it up
module.exports = router;

const profile = require( './routes/api/profile' );
app.use( '/api/profile', profile );

// Combine react and node js servers while deploying( YOU MIGHT HAVE ALREADY DONE THIS BEFORE
// What you need to do is make the build directory on the heroku, which will contain the index.html of your react app and then point the HTTP request to the client/build directory

if ( process.env.NODE_ENV === 'production' ) {
    // Set a static folder
    app.use( express.static( 'client/build' ) );
    app.get( '*', ( req, res ) => res.sendFile( path.resolve( __dirname, 'client', 'build', 'index.html' ) ) );

}

// Set up a port
const port = process.env.PORT || 5000;

app.listen( port, () => console.log( `Server running on port: ${port}` ) );

профиль. js

const aws = require( 'aws-sdk' );
const multerS3 = require( 'multer-s3' );
const multer = require('multer');
const path = require( 'path' );

const router = express.Router();

/**
 * PROFILE IMAGE STORING STARTS
 */
const s3 = new aws.S3({
    accessKeyId: 'XXXXXXXXX',
    secretAccessKey: 'XXXXXXXXXXX',
    Bucket: 'XXXXXXXXX'

   });
/**
 * Single Upload
 */
const profileImgUpload = multer({
    storage: multerS3({
     s3: s3,
     bucket: 'rodnewbucket',
     acl: 'public-read',
     key: function (req, file, cb) {
      cb(null, path.basename( file.originalname, path.extname( file.originalname ) ) + '-' + Date.now() + path.extname( file.originalname ) )
     }
    }),
    limits:{ fileSize: 2000000 }, // In bytes: 2000000 bytes = 2 MB
    fileFilter: function( req, file, cb ){
     checkFileType( file, cb );
    }
   }).single('profileImage');

/**
 * Check File Type
 * @param file
 * @param cb
 * @return {*}
 */
function checkFileType( file, cb ){
    // Allowed ext
    const filetypes = /jpeg|jpg|png|gif/;
    // Check ext
    const extname = filetypes.test( path.extname( file.originalname ).toLowerCase());
    // Check mime
    const mimetype = filetypes.test( file.mimetype );if( mimetype && extname ){
     return cb( null, true );
    } else {
     cb( 'Error: Images Only!' );
    }
   }

/**
 * @route POST api/profile/business-img-upload
 * @desc Upload post image
 * @access public
 */
router.post( '/profile-img-upload', ( req, res ) => {profileImgUpload( req, res, ( error ) => {
    console.log( 'requestOkokok', req.file );
    console.log( 'error', error );
    if( error ){
     console.log( 'errors', error );
     res.json( { error: error } );
    } else {
     // If File not found
     if( req.file === undefined ){
      console.log( 'Error: No File Selected!' );
      res.json( 'Error: No File Selected' );
     } else {
      // If Success
      const imageName = req.file.key;
      const imageLocation = req.file.location;( {
       image: imageName,
       location: imageLocation
      });
     }
    }
   });
  });// End of single profile upload/**

  module.exports = router;

Дом. js

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

class Home extends Component {
    constructor( props ) {
        super( props );
        this.state = {
         selectedFile: null,
         selectedFiles: null
        }
    }

    singleFileChangedHandler = ( event ) => {
        //console.log( event.target.files );
        this.setState({
         selectedFile: event.target.files[0]
        });
    };

    singleFileUploadHandler = ( event ) => {
        const data = new FormData();
        // If file selected
        if ( this.state.selectedFile ) {data.append( 'profileImage', this.state.selectedFile, this.state.selectedFile.name );axios.post( '/api/profile/profile-img-upload', data, {
           headers: {
            'accept': 'application/json',
            'Accept-Language': 'en-US,en;q=0.8',
            'Content-Type': `multipart/form-data; boundary=${data._boundary}`,
           }
          })
           .then( ( response ) => {if ( 200 === response.status ) {
            // If file size is larger than expected.
            if( response.data.error ) {
                if ( 'LIMIT_FILE_SIZE' === response.data.error.code ) {
                    this.ocShowAlert( 'Max size: 2MB', 'red' );
                } else {
                    console.log( response.data );// If not the given file type
                    this.ocShowAlert( response.data.error, 'red' );
                }
                } else {
                    // Success
                    let fileName = response.data;
                    console.log( 'fileName', fileName );
                    this.ocShowAlert( 'File Uploaded', '#3089cf' );
                }
            }
           }).catch( ( error ) => {
                // If another error
                this.ocShowAlert( error, 'red' );
            });
        } else {
            // if file not selected throw error
            this.ocShowAlert( 'Please upload file', 'red' );
        };
    }

    // ShowAlert Function
    ocShowAlert = ( message, background = '#3089cf' ) => {
        let alertContainer = document.querySelector( '#oc-alert-container' ),
            alertEl = document.createElement( 'div' ),
            textNode = document.createTextNode( message );
            alertEl.setAttribute( 'class', 'oc-alert-pop-up' );
            $( alertEl ).css( 'background', background );
            alertEl.appendChild( textNode );
            alertContainer.appendChild( alertEl );
            setTimeout( function () {
            $( alertEl ).fadeOut( 'slow' );
            $( alertEl ).remove();
        }, 3000 );
    };


    render() {
        console.log( this.state );
        return(
            <div className="container">
                {/* For Alert box*/}
                <div id="oc-alert-container"></div>
                <div className="card border-light mb-3 mt-5" style={{ boxShadow: '0 5px 10px 2px rgba(195,192,192,.5)' }}>
                    <div className="card-header">
                        <h3 style={{ color: '#555', marginLeft: '12px' }}>Single Image Upload</h3>
                        <p className="text-muted" style={{ marginLeft: '12px' }}>Upload Size: 250px x 250px ( Max 2MB )</p>
                    </div>
                    <div className="card-body">
                        <p className="card-text">Please upload an image for your profile</p>
                        <input type="file" onChange={this.singleFileChangedHandler}/>
                        <div className="mt-5">
                            <button className="btn btn-info" onClick={this.singleFileUploadHandler}>Upload!</button>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}

export default Home;

Пакет. json

"name": "react-node-boilerplate",
  "version": "1.0.0",
  "description": "A React Js and Node Js boilerplate for building a new project. It uses create-react-app",
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "server": "nodemon server.js",
    "client-install": "npm install --prefix client",
    "client": "npm start --prefix client",
    "dev": "concurrently \"npm run server\" \"npm run client\""
  },
  "engines": {
    "node": "10.10.0"
  },
  "author": "Imran Sayed",
  "license": "ISC",
  "dependencies": {
    "aws-sdk": "^2.652.0",
    "body-parser": "^1.18.3",
    "concurrently": "^4.0.1",
    "express": "^4.16.3",
    "mongoose": "^5.3.1",
    "multer": "^1.4.2",
    "multer-s3": "^2.9.0",
    "path": "^0.12.7",
    "url": "^0.11.0",
    "validator": "^10.8.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.2"
  }
}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...