问题描述
限时送ChatGPT账号..我正在尝试在 nodejs 中使用 express 制作 API.
I'm trying to make an API using express in nodejs.
此 api 应收到带有照片的请求,并将该照片发布到 Firebase 存储.
This api should get a request with a photo and post that photo to firebase storage.
主要问题是由于某种原因,我发送的请求正文为空.
The main problem is that for some reason the body of the requests I send are empty.
这是服务器的代码:
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,但它似乎已被弃用
I've tried using body-parser but it seems to be deprecated
推荐答案
你必须在 formData 中从前端发送一个图像.
you have to send an image from the front end in formData.
const data = new FormData();
data.append('myFile', 'Image Upload');
在后端使用multer将文件上传到服务器.首先通过以下方式安装multer:npm i multer
In back end use multer to upload file to server. first install multer by : 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);
});
这是使用 multer 上传文件的正确指南表达js
这篇关于空体Api rest express node js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论