【问题标题】:React single file upload with Node, Express, Multer and store to Google Cloud Storage使用 Node、Express、Multer 响应单个文件上传并存储到 Google Cloud Storage
【发布时间】:2020-10-18 02:58:55
【问题描述】:

我为我的 3D 项目建立了一个网站。我想将图像上传到 React 网络并将其存储在 Google Cloud Storage 存储桶中。当我使用 Postman 发出请求但未收到从前端上传图像的请求时,后端服务器似乎可以将图像发送到 Google Cloud Storage。我遇到以下问题:

1) xhr.js:184 POST http://localhost:9001/uploads 500 (Internal Server Error)

2) createError.js:16 Uncaught (in promise) Error: Request failed with status code 500
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:69)

我的上传代码在 Modeling.js 中:

import React, {Component} from 'react';
import axios from 'axios';
import { toast } from 'react-toastify';

export class modeling extends Component {
  constructor(props){
    super(props);
    this.fileChangedHandler = this.fileChangedHandler.bind(this);
    this.uploadHandler = this.uploadHandler.bind(this);

    this.state={
      selectedFile: ''
    }
  }

  fileChangedHandler = event => {
    this.setState({
      selectedFile: event.target.files[0],
    })
  }

  uploadHandler = event => {
    event.preventDefault()
    const data = new FormData() 
    data.append('image', this.state.selectedFile)
    axios.post("http://localhost:9001/uploads", data, { 
    })
      .then(res => { // then print response status
        console.log(res.statusText)
      })
    }
  render(){
    return (
        <h3>Upload a 2D image to get a 3D model</h3>         
        <input className="btn btn-secondary" type="file" onChange={this.fileChangedHandler} />
         <button className="btn btn-primary" onClick={this.uploadHandler} id="renderButton">Uplooad</button>
    )
  }
}

export default modeling

我的后端代码是:

const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const multer = require('multer')

const uploadImage = require('./helpers/helpers')

const app = express()

const multerMid = multer({
  storage: multer.memoryStorage(),
  limits: {
    // no larger than 5mb.
    fileSize: 5 * 1024 * 1024,
  },
});

app.use(cors());
app.disable('x-powered-by')
app.use(multerMid.single('file'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))

app.post('/uploads', async (req, res, next) => {
  try {
    const myFile = req.file
    const imageUrl = await uploadImage(myFile)

    res
      .status(200)
      .json({
        message: "Upload was successful",
        data: imageUrl
      })
  } catch (error) {
    next(error)
  }
})

app.use((err, req, res, next) => {
  res.status(500).json({
    error: err,
    message: 'Internal server error!',
  })
  next()
})

app.listen(9001, () => {
  console.log('app now listening for requests!!!')
})

我已经在 Postman 中测试了后端,上传成功,并且图像也显示在我的 Google Cloud Storage 存储桶中,如下图所示

谁能给我一些建议,说明为什么我的前端无法接收到在 URL“http://localhost:9001/uploads”上上传的 HTTP 发布请求以及如何解决这个问题?我真的很感谢你的帮助。非常感谢!

【问题讨论】:

  • 使用箭头函数时,无需在构造函数中绑定它们。去掉 super(props) 之后的那两行
  • 另外,在你的 axios post 请求中,你需要添加一个 .catch(error => console.log(error))
  • 还是出现同样的错误。

标签: node.js reactjs express google-cloud-storage multer


【解决方案1】:

您可以尝试像这样向您的函数添加 async 和 await 吗?

uploadHandler = async (event) => { 
    event.preventDefault() 
    const data = new FormData() 
    data.append('image', 
    this.state.selectedFile) 
    await axios.post("./uploads", 
    data, { }).then(res => { 
    // then print response status 
    console.log(res.statusText) 
    }).catch(error => 
    console.log(error)) 
}

【讨论】:

猜你喜欢
  • 2017-11-12
  • 2017-03-01
  • 2021-12-30
  • 1970-01-01
  • 2020-11-12
  • 1970-01-01
  • 2021-03-27
  • 2018-10-31
  • 1970-01-01
相关资源
最近更新 更多