reactjs 如何使用url将图像属性发送到服务器?

qvtsj1bj  于 2023-08-04  发布在  React
关注(0)|答案(1)|浏览(89)

我只发送数据。以下是我的数据:

export const cabin = {
    name: '001',
    maxCapacity: 2,
    regularPrice: 250,
    discount: 0,
    image: './cabins/cabin-001.jpg',
    description:
      'aaaaaaa',
}

字符串
我使用axios发送此数据:

async function createCabins() {
  await axios.post("http://localhost:3005/cabins",{
    cabin
  }).catch(error=>{
    if (error) console.log(error.message);
  });
}


在服务器上,我的帖子路由如下:

router.post('/', upload.single('image'), async (req,res)=>{
    try {
        const data = await Cabins.create({...req.body, image: req.file.path})
        res.status(200).json(data)
    } catch (error) {
        console.log(error)
        res.status(400).json(error)        
    }
})


这里的错误我只发送图像URL。如何发送图片 prop 到服务器。我尝试了很多这样的方法:

import cabin1 from './cabins/cabin-001.jpg'


或者是

image: require(''./cabins/cabin-001.jpg')


这些对我没用

jxct1oxe

jxct1oxe1#

我认为在通过axios发送之前应该序列化对象。所以应该使用JSON.stringify()函数。
请确认终点是否正确:在这里,您指定了/cabins,但在服务器代码中,它只是/
我还建议您将端点重命名为single,因此将cabins更改为cabin

await axios.post("http://localhost:3005/cabins",{
    JSON.stringify( cabin )
  })

字符串

相关问题