react中的formdata,当我发送formdata到后端express时使null保持无效

发布于 2025-01-17 12:45:54 字数 1440 浏览 0 评论 0原文

当我从前端发送数据时,我在后端收到空值。我正在发送 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)
        })

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:

    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);
        });

    }

Backend:

// 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)
        })

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

﹂绝世的画 2025-01-24 12:45:54

它是空的,因为在服务器上您有一个 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,但由于您没有上传文件,

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

因此请使用 body-parser,因为 FormData 将数据发送为 < code>multipart/form-data,bodyParser无法解析它,所以需要用URLSearchParams将其转为URL编码的字符串

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

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:

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)
})

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

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

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

fetch('http://localhost:5000/shortUrls', {
    method: 'post',
    body: new URLSearchParams(formData)
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文