React中的formData,当我将formData发送到后端Express时,它变为null



当我从前端发送数据时,我在后端收到null。我正在发送2个字符串数据URL和日期,所以我认为我不需要使用额外的中间件来接收值。

前端:

const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
const today = new Date();
const date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
const formData = new FormData();
formData.append('url', url);
formData.append('date', date);
console.log(url, date);
fetch('http://localhost:5000/shortUrls', {
method: 'post',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.insertedId) {
alert('Link Added')
setLoadings(true)
}
})
.catch(error => {
console.error('Error:', error);
});
}

后端:

// middleware
const app = express();
app.use(cors())
app.use(express.json())
app.post('/shortUrls', async (req, res) => {
const uniqueUrl = shortId({ url: req.body.url })
console.log(req);
const details = {
short: uniqueUrl,
full: req.body.url,
clicks: 0,
date: req.body.date,
}
const result = await AffiliateLinksCollection.insertOne(details)
res.json(result)
})

它是空的,因为在服务器上有一个json解析器,但您发送的是multipart/form-data请求,并且没有解析器来处理它。

由于您没有上传文件,最简单的方法是发送json请求:

e.preventDefault()
const today = new Date();
const date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
// use object
const formData = {url, date};
console.log(url, date);
// post json
fetch('http://localhost:5000/shortUrls', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})

如果要使用FormData,则需要在服务器上包含解析器。通常,这是multer,但由于您没有上传文件,请使用body-parser

app.use(bodyParser.urlencoded({ extended: true }));

但是,由于FormDatamultipart/form-data的形式发送数据,bodyParser无法解析它,因此需要使用URLSearchParams将其转换为URL编码的字符串

fetch('http://localhost:5000/shortUrls', {
method: 'post',
body: new URLSearchParams(formData)
})

最新更新