Im want to add sitemap route to my react website so I fetch the sitemap data and want to render a xml when user enter www.website.om/sitemap so I have this code in the backend:
const generateSitemap = async (req: Request, res: Response) => { try { const response = await fetch('https://www.mysitemapdata.app/sitemap.xml'); const xmlData = await response.text(); res.header('Content-Type', 'application/xml'); res.send(xmlData); } catch (error) { console.error('Error fetching the sitemap:', error); res.status(500).send('Error fetching the sitemap'); }};
and I get this error in the backend terminal:
Error: Cannot set headers after they are sent to the client at new NodeError (node:internal/errors:405:5) at ServerResponse.setHeader (node:_http_outgoing:648:11) at ServerResponse.header (C:\Users\97254\Desktop\FeelThere\user-server-production\node_modules\express\lib\response.js:795:10) at ServerResponse.send (C:\Users\97254\Desktop\FeelThere\user-server-production\node_modules\express\lib\response.js:175:12) at generateSitemap (C:\Users\97254\Desktop\FeelThere\user-server-production\src\controllers\auth.controller.ts:114:25) at processTicksAndRejections (node:internal/process/task_queues:95:5) { code: 'ERR_HTTP_HEADERS_SENT}
and this error in the browser console:POST http://192.168.1.116/auth/sitemap net::ERR_CONNECTION_REFUSED
this is the frontend:
const FetchExternalXML = () => { const [xmlData, setXmlData] = useState<string | null>(null); useEffect(() => { const fetchSitemap = async () => { try { const res = await fetch("https://www.feelthere.app/sitemap.xml"); const text = await res.text(); setXmlData(text); await userService.sitemap(xmlData) } catch (err) { console.log("Error while fetching sitemap:", err); } }; fetchSitemap(); }, []); return xmlData ? (<div dangerouslySetInnerHTML={{ __html: xmlData }} /> ) : (<p>Loading sitemap...</p> );};
const sitemap = (data: any) => handlePostRequest(`auth/sitemap`, data)
My goal is to render this page as xml and not just html file
I tried the code above and its looks that its convert the header to xml but its doesn't