【问题标题】:I am trying to send a image file to my backend server but when it arrives I receive an empty object我正在尝试将图像文件发送到我的后端服务器,但是当它到达时我收到一个空对象
【发布时间】:2023-01-27 23:05:40
【问题描述】:

我正在尝试制作一个表单,将图像发送到后端并将其保存在我的本地磁盘上,但是当我将图像文件发送到后端时,它显示一个空对象。

前端

import Axios from 'axios'
import { useForm } from 'react-hook-form'

const Create_post = () => {

    const { register, handleSubmit } = useForm()

    const onSubmit = (data) => {
        let post = {
            file:data.image[0]
        }
        handleApi(post)
    }

    const handleApi = (post) => {

        console.log(post)

        Axios.post('http://localhost:3001/api/post', post).then((response) => {
            console.log(response)
        })
    }

    return (  
        <div>
            <form onSubmit={handleSubmit(onSubmit)}>      
                <input type='text'/>
                <div>
                    <div>
                        <div>
                            <input type='file' name='fileInput' {...register(
                                'image', {required: true}
                            )}/>
                        </div>
                    </div>
                </div>
                <input type='submit' name='submitButton'/>      
            </form>
        </div>
    );
}
 
export default Create_post;

后端

const express = require('express')
const app = express()
const cors = require('cors')
const sql = require('mysql')
const bodyParser = require('body-parser')
const imgUpload = require('express-fileupload')

const db = sql.createPool({
    host:'localhost',
    user:'root',
    password:'password',
    database:'photo_website_database'
})

app.use(cors())
app.use(express.json())
app.use(bodyParser.urlencoded({extended:true}))
app.use(imgUpload())

app.post('/api/post/', (req, res)=>{
    let post = req.body
    console.log(post.file)
})

app.listen(3001,()=>{
    console.log('running on port 3001')  
})

..................................................... ............................................................

【问题讨论】:

    标签: node.js reactjs express axios


    【解决方案1】:

    如果您要发送文件,则必须将其作为 formData 发送。

    将您的数据转换为 formData 然后发送。

    此外,您的内容类型应该是 multipart/form-data,但我认为当您给他 formData 时,axios 会自动为您添加该标题

    您可以在网上找到如何将对象转换为 formData Convert JS Object to form data

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-05
      • 2015-09-23
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-26
      • 1970-01-01
      • 2021-12-22
      相关资源
      最近更新 更多