我试图上传PDF文件(简历)在未来的js,一切都很好,根据我的期望,但在后端时,我
console.log(req.data)
它告诉我
[object:object]
注意当我console.log数据在前端它的工作正常,我看到所有的数据,包括文件的形式,但在后端我无法获得该数据
1.我尝试在下一个API中将bodyparser配置为false,如果我这样做,我将不会在后端接收任何数据
如何解决此问题
发布请求
export const apply_job = async (formData) => {
console.log(formData)
try {
const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/job/applyJob`, {
method: 'POST',
headers : {
'Content-Type': 'multipart/form-data',
},
body: formData,
});
const data = await res.json();
return data;
} catch (error) {
console.log('error in apply job (service) => ', error);
}
}
前端代码
import NavBar from '@/components/NavBar';
import { apply_job } from '@/Services/job';
import { useRouter } from 'next/router';
import React, { useState } from 'react'
import { useDispatch, useSelector } from 'react-redux';
import { toast, ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
export default function ApplyJob() {
const router = useRouter()
const dispatch = useDispatch();
const { id } = router.query
const user = useSelector(state => state.User.userData)
const [formData, setFormData] = useState({ name: '', email: "", about: '', job: id, user: user?._id, cv: null })
const [error, setError] = useState({ name: '', email: "", about: '', job: '', user: '', cv: '' });
const handleSubmit = async (e) => {
e.preventDefault();
if (!formData.name) {
setError({ ...error, name: "Name Field is required" })
return;
}
if (!formData.email) {
setError({ ...error, email: "Email Field is required" })
return;
}
if (!formData.user) {
return toast.error('Please Login First')
}
if (!formData.job) {
return toast.error('Please Follow Apply Process ')
}
if (!formData.about) {
setError({ ...error, about: "About Field is required" })
return;
}
if (!formData.cv) {
setError({ ...error, cv: "Please Upload CV" })
return;
}
console.log(formData)
const res = await apply_job(formData);
// if (res.success) {
// toast.success(res.message)
// } else {
// toast.error(res.message)
// }
}
return (
<>
<NavBar />
<div className='w-full py-20 flex items-center justify-center flex-col'>
<h1 className='text-xl mt-4 uppercase tracking-widest border-b-2 border-b-indigo-600 py-2 font-semibold mb-8 md:text-2xl lg:text-4xl'>Enter Your Info</h1>
<form encType="multipart/form-data" onSubmit={handleSubmit} className="sm:w-1/2 w-full px-4 mx-4 h-full" >
<div className='w-full mb-4 flex flex-col items-start justify-center'>
<label htmlFor="title" className='mb-1 text-base font-semibold'>Name :</label>
<input onChange={(e) => setFormData({ ...formData, name: e.target.value })} type="text" id='title' className='w-full py-2 px-3 mb-2 border border-indigo-600 rounded' placeholder='Enter Name ' />
{
error.name && <p className="text-sm text-red-500">{error.name}</p>
}
</div>
<div className='w-full mb-4 flex flex-col items-start justify-center'>
<label htmlFor="email" className='mb-1 text-base font-semibold'>Email :</label>
<input onChange={(e) => setFormData({ ...formData, email: e.target.value })} type="email" id='email' className='w-full py-2 px-3 mb-2 border border-indigo-600 rounded' placeholder='Enter Email' />
{
error.email && <p className="text-sm text-red-500">{error.email}</p>
}
</div>
<div className='w-full mb-4 flex flex-col items-start justify-center'>
<label htmlFor="description" className='mb-1 text-base font-semibold'>About :</label>
<textarea onChange={(e) => setFormData({ ...formData, about: e.target.value })} type="description" id='description' className='w-full py-2 px-3 mb-2 border border-indigo-600 rounded' placeholder='Enter description' />
{
error.about && <p className="text-sm text-red-500">{error.about}</p>
}
</div>
<div className='w-full mb-4 flex flex-col items-start justify-center'>
<label htmlFor="file" className='mb-1 text-base font-semibold'>Upload CV :</label>
<input name='cv' onChange={(e) => setFormData({ ...formData, cv: e.target.files[0] })} type="file" id='file' className='w-full py-2 px-3 mb-2 border border-indigo-600 rounded' placeholder='Enter Email' />
{
error.cv && <p className="text-sm text-red-500">{error.cv}</p>
}
</div>
<button type="submit" className='w-full py-2 rounded bg-indigo-600 text-white font-semibold tracking-widest'>Submit</button>
</form>
</div>
<ToastContainer />
</>
)
}
后台代码
import ConnectDB from '@/DB/connectDB';
import AppliedJob from '@/models/ApplyJob';
import Joi from 'joi';
const schema = Joi.object({
name: Joi.string().required(),
email: Joi.string().email().required(),
about: Joi.string().required(),
job: Joi.string().required(),
user: Joi.string().required(),
});
export const config = {
api: {
bodyParser: {
sizeLimit: '50mb' // Set desired value here
}
}
}
export default async (req, res) => {
await ConnectDB();
const data = req.body;
console.log(data)
// const { name, email, job, user, about , cv} = data;
// const { error } = schema.validate({ name, email, job, user, about});
// if (error) return res.status(401).json({ success: false, message: error.details[0].message.replace(/['"]+/g, '') });
// try {
// const creatingUser = await AppliedJob.create({user , title,description , salary , company , email , job_category , job_type , job_experience , job_vacancy , job_deadline });
// return res.status(200).json({ success: true, message: "Job Posted Successfully !" })
// } catch (error) {
// console.log('Error in posting a job (server) => ', error);
// return res.status(500).json({ success: false, message: "Something Went Wrong Please Retry Later !" })
// }
}
1条答案
按热度按时间xiozqbni1#
在你的前端代码中,你需要像这样初始化一个Javascript
formData
对象:const formData = new FormData()
在发送数据之前,您需要将每个输入添加到
formData
对象,例如formData.append("name", nameInput)
然后在请求体中发送formData对象。不需要content-type
标头,因为浏览器会自动检测FormData
对象并为multipart/form-data
标头分配边界在后端代码中,需要使用
formidable
解析发送到端点的表单数据。它应该看起来像这样: