【问题标题】:Empty body Api rest express node js空体Api rest express node js
【发布时间】:2021-08-10 18:40:27
【问题描述】:

我正在尝试在 nodejs 中使用 express 制作 API。

此 api 应获取包含照片的请求并将该照片发布到 Firebase 存储。

主要问题是由于某种原因我发送的请求正文是空的。

这是服务器的代码:

const express = require("express");
const morgan  = require("morgan")
const cors    = require('cors')

const app = express();

// Settings

app.set('port', process.env.PORT || 3000)
app.set('json spaces', 4)

// middleware

app.use(morgan("dev"))
app.use(express.json())
app.use(express.urlencoded({extended: true}))
app.use(cors({origin: "http://localhost:3001"}))

// routes

app.use(require("./routes/index"))

app.listen(app.get('port'), () => {
    console.log("Server using port " + app.get('port'));
});

路线

const { Router } = require('express')

const router  = Router()

router.post('/postImage', async (req, res) => {
    try {
        const image = req.body

        console.log(image)  // Here I only get an epty object "{}"

        return res.status(200).json(image)
    }
    catch(error) {
        console.log(error)
        return res.status(500).json({error})
    }
})

module.exports = router

客户端

    const postImage = async (image) => {
        console.log(image)  // Here I get the image data

        const response = await fetch("http://localhost:3000/postImage", {
            method: "POST",
            body: {message: "image"}
        })

        const data = await response.json()
    }

我尝试过使用 body-parser,但它似乎已被弃用

【问题讨论】:

  • 你不认为你需要有上传文件的API,当你做console.log(image) // Here I get the image data时,你看到的消息是什么。那是文件路径吗?
  • 我看到的是一个文件对象(路径、名称、预览、大小...)
  • 我认为你应该在你的应用中使用 bodyparser
  • 那你应该勾选 express 支持文件上传示例
  • 您必须决定该图像是您的请求的整个正文,还是该图像应在正文中进行编码,如 HTML“上传文件”按钮的情况。在后一种情况下,您需要一个 body-parser 中间件。您的决定可能取决于 Firebase API 对图像数据的预期。

标签: javascript node.js api rest express


【解决方案1】:

你必须在 formData 中从前端发送一个图像。

const data = new FormData();
data.append('myFile', 'Image Upload');

在后端使用 multer 将文件上传到服务器。 首先通过以下方式安装 multer:npm i multer

const multer = require("multer");
//Configuration for Multer
const upload = multer({ dest: "public/files" });
app.post("/api/uploadFile", upload.single("myFile"), (req, res) => {
// Stuff to be added later
console.log(req.file);
});

Here is a proper Guide to upload file using multer express js

【讨论】:

    猜你喜欢
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    • 2017-06-10
    • 2017-12-02
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    相关资源
    最近更新 更多