When I send data from the frontend I receive null in the backend. I am sending 2 string data URLs and dates so I don’t think that I need to use extra middleware for receiving the values.
Frontend:
JavaScript
x
26
26
1
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
2
e.preventDefault()
3
const today = new Date();
4
const date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
5
const formData = new FormData();
6
formData.append('url', url);
7
formData.append('date', date);
8
console.log(url, date);
9
10
fetch('http://localhost:5000/shortUrls', {
11
method: 'post',
12
body: formData
13
})
14
.then(response => response.json())
15
.then(data => {
16
if (data.insertedId) {
17
alert('Link Added')
18
setLoadings(true)
19
}
20
})
21
.catch(error => {
22
console.error('Error:', error);
23
});
24
25
}
26
Backend:
JavaScript
1
18
18
1
// middleware
2
const app = express();
3
app.use(cors())
4
app.use(express.json())
5
6
app.post('/shortUrls', async (req, res) => {
7
const uniqueUrl = shortId({ url: req.body.url })
8
console.log(req);
9
const details = {
10
short: uniqueUrl,
11
full: req.body.url,
12
clicks: 0,
13
date: req.body.date,
14
}
15
const result = await AffiliateLinksCollection.insertOne(details)
16
res.json(result)
17
})
18
Advertisement
Answer
it’s empty because on the server you have a json
parser, but you’re sending a multipart/form-data
request, and there is no parser to process it.
as you’re not uploading a file, the easiest way would be to send a json
request:
JavaScript
1
17
17
1
e.preventDefault()
2
const today = new Date();
3
const date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
4
5
// use object
6
const formData = {url, date};
7
console.log(url, date);
8
9
// post json
10
fetch('http://localhost:5000/shortUrls', {
11
method: 'post',
12
headers: {
13
'Content-Type': 'application/json'
14
},
15
body: JSON.stringify(formData)
16
})
17
if you want to use FormData
, you need to include parser on the server. usually, this is multer
, but as you’re not uploading a file, use body-parser
JavaScript
1
2
1
app.use(bodyParser.urlencoded({ extended: true }));
2
however, as FormData
is sending data as multipart/form-data
, bodyParser
cannot parse it, so you need to turn it into URL-encoded string with URLSearchParams
JavaScript
1
5
1
fetch('http://localhost:5000/shortUrls', {
2
method: 'post',
3
body: new URLSearchParams(formData)
4
})
5