我正在尝试使用formData从React前端上传信息,我使用postman检查了后端,一切正常,但是formData没有将文件传递给后端。这是我的代码
React前端组件
import axios from 'axios'
import React, { useState } from 'react'
function NotificationSecond() {
let server = "http://localhost:3456";
let address = `${server}/user/notification`
const [Data, setData] = useState({
assigned_to:"",
message:""
})
const [response, setresponce] = useState();
let submitter = (e)=>{
e.preventDefault();
let forForm = new FormData();
forForm.append('assigned_to',Data.assigned_to)
forForm.append('message',Data.message)
axios({
method:"post",
url:address,
data:forForm,
headers: {"Content-Type": "multipart/form-data" },
}).then((data)=>{
setresponce(data.data)
}).catch((err)=>{
console.log(err)
})
}
let inputHandler = (e)=>{
switch (e.target.value) {
case "assigned_to":setData((pre)=>{return {...pre,assigned_to:e.target.value}})
break;
case "message":setData((pre)=>{return {...pre,message:e.target.value}})
break;
default:
break;
}
}
if(response){
return
this is response
}else{
return (
)
}
}
export default NotificationSecond
后端控制器
import Econnection from "../server.js";
let notification =(req,res)=>{
const {assigned_to,message}=req.body
let value = [assigned_to,message];
let notificationAdder = `INSERT INTO notification(assigned_to,message) VALUES (?)`;
Econnection.query(notificationAdder,[value],(err)=>{
if(err){
console.log(err)
res.send('上传通知不成功')
}else{
res.send({
forThanking : `上传成功,谢谢!`,
forHomePageReturn: `点击这里返回首页`
})
}
})
}
export default notification;
后端路由
import express from 'express';
import notification from '../Controaller/noticationControler.js';
let notificationRoute = express.Router();
notificationRoute.post('/notification',notification)
在此处输入代码导出默认通知路由我上传了后端,以防万一,但是根据我的测试,后端的所有事情都正常工作,所有的switch和state也正常工作,但是我不认为axios通过创建的路由将数据发布到mysql数据库中,该数据库仅包含两个列,分别为“assigned_to”和“message”。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
问题是表单数据方法没有附加到输入值上;我创建了一个具有不同名称的对象,并将对象名称传递给axios方法,这样就可以正常工作了。还从axios中删除了头部部分。
let file = { assigned_to: Data.assigned_to, message : Data.message } axios({ method:"post", url:address, data:file, }) .then((data) => { setresponce(data.data) }) .catch((err) => { console.log(err) }) }