通过react从nodejs服务器下载文件时出现错误

问题描述 投票:0回答:1

我想从nodejs服务器应用程序下载用户上传的pdf文件。

这是我在nodejs中的路线:

// @desc handle pdf download
// @Route Post /cv-download
router.post('/cv-download', authenticated , isJobSeeker , jobseekCtrl.downloadFile);

我的 Nodejs 控制器中的 downloadFile 控制器是:

class jobseekerCtrl {
    static downloadFile = async (req , res , next)=>{ 
        const cvName = req.body.cv_name;
        const userId = req.userId;
    
        const filePath =  path.join("./upload/" , userId ,  cvName);
             
        try{
          res.download(filePath);
        }
        catch(err){
          next(err);
        }   
      };
    }
    module.exports = jobseekerCtrl;

在我的 reractjs 应用程序中,我有以下组件:

const JobseekerInfo = () => {
    const [userCv, setUserCv] = useImmer({});
    const [userPDFs, setUserPDFs] = useImmer([]);
    const { loading, setLoading } = useContext(AppContext);

    useEffect(() => {
        const fetchCV_Data = async () => {
            const storedToken = localStorage.getItem('token');
            setLoading(true);
            try {
                const { data: CV_data, status: CV_status } = await getJobSeekerCV(JSON.parse(storedToken));
                if (CV_status === 200) {
                    if (CV_data) {
                        const { data: PDF_data, status: PDF_status } = await getJobSeekerPDFs(JSON.parse(storedToken));
                        if (CV_status === 200) {
                            if (CV_data) {
                                setUserCv(CV_data.myCV);
                                setUserPDFs(PDF_data.PDFs);
                            }
                        }
                    }
                }
            } catch (err) {

            }
            finally {
                setLoading(false);
            }

        }
        fetchCV_Data();
    }, []);

    const downloadCV = async (pdfName) => {
        const storedToken = localStorage.getItem('token');
        await downloadPDF(pdfName, JSON.parse(storedToken));
    }

    return (
        <div className="text-light">
            {
                loading ? (<div className='text-center'><Spinner /></div>) :
                    <div className="modal-body styled-table  rounded p-3" >
                        <dl className='row'>
                            {/* Some Codes here */}

                        </dl>
                        <hr />
                        <div className='text-center mx-auto'>
                            <table className='table table-hover table-striped w-auto d-inline'>
                                <thead>
                                    <tr>
                                        <th>Row</th>
                                        <th>Original Name</th>
                                        <th>Date</th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {userPDFs.map((pdf, index) => (
                                        <tr key={index}>
                                            <td>{index + 1}</td>
                                            <td>{pdf.serverName}</td>
                                            <td>{Intl.DateTimeFormat("en").format(new Date(pdf.createdOn))}</td>
                                            <td>
                                                <div dir='ltr' className='btn-group'>
                                                    <button className='btn btn-danger'><i className='fa fa-trash'></i></button>

                                                    <button className='btn btn-success' onClick={() => downloadCV(pdf.serverName)}><i className='fa fa-download'></i></button>
                                                </div>
                                            </td>
                                        </tr>
                                    ))
                                    }
                                </tbody>
                            </table>
                        </div>


                    </div>
            }
        </div>
    );
}

export default JobseekerInfo;

最后我的下载PDF服务发布了一些信息:

//@desc Post Download a PDF
//@route http://localhost:9000/cv-download
export const downloadPDF= (name, token)=>{
    const headers = { 'Authorization': `Bearer ${token}` };
    const url = `${SERVER_URL}/cv-download`;
    return axios.post(url , {cv_name: name}, {headers: headers});
}

我的问题是当我点击我想下载pdf文件的下载按钮时,无法下载它。

出了什么问题,我该如何解决这个问题?顺便说一下,当我在邮递员上测试它时,它有效。

node.js reactjs download
1个回答
0
投票

没有人回答,所以我想分享一下我自己的解决方案。我使用了“react-router-dom”模块中的链接并更改了 post 方法来下载它。

在reactjs中:

 <Link className='btn btn-success'
 to={`http://localhost:9000/cv-download/${userToken}?cv_name=${pdf.serverName}`} download="Example-PDF-document"
 target="_blank"
 rel="noreferrer"
 >
   <i className='fa fa-download'></i>
</Link>

nodejs路线:

// @desc handle pdf download
// @Route Get /cv-download
router.get('/cv-download/:token', authenticated , isJobSeeker , jobseekCtrl.downloadFile);

和nodejs控制器:

 static downloadFile = async (req , res , next)=>{ 
    const cvName = req.query.cv_name;
    const userId = req.userId;

    const filePath =  path.join("./upload/" , userId ,  cvName);
         
    try{
      res.download(filePath);
    }
    catch(err){
      next(err);
    }   

  };
© www.soinside.com 2019 - 2024. All rights reserved.