如何修复Node.js中‘Failed to load resource: 403(Forbidden)’错误
解决Node.js项目中403 Forbidden错误的方案
先梳理你代码里的问题,再一步步排查403错误:
1. 修复模板替换的低级错误
你的replaceTemplate函数有两个明显问题:
- 第一行把
product.name用单引号包裹,导致渲染后页面显示字符串product.name而非实际产品名称; - 后续替换都用
temp.replace而非output.replace,会覆盖之前的修改,只有最后一次替换生效。
修正后的函数:
const replaceTemplate = (temp, product) => { let output = temp.replace(/{%PRODUCTNAME%}/g, product.name); output = output.replace(/{%IMAGE%}/g, product.image); output = output.replace(/{%PRICE%}/g, product.price); output = output.replace(/{%FROM%}/g, product.from); output = output.replace(/{%NUTRIENTS%}/g, product.nutrients); output = output.replace(/{%QUANTITY%}/g, product.quantity); output = output.replace(/{%DESCRIPTION%}/g, product.description); output = output.replace(/{%ID%}/g, product.id); return output }
2. 添加静态资源路由(核心解决403/404问题)
你的服务器仅处理了/、/overview、/product、/api几个路径,页面加载图片等静态资源时,服务器无对应处理逻辑,部分环境下会返回403错误。假设图片存放在./img文件夹,添加以下路由处理:
const server = http.createServer((req, res) => { const pathName = req.url; // Overview page if(pathName === '/' || pathName === '/overview') { // 原有逻辑不变 // Product page }else if(pathName === '/product'){ // 原有逻辑不变 // API }else if (pathName === '/api'){ // 原有逻辑不变 // 处理静态资源(图片等) }else if (pathName.startsWith('/img/')) { fs.readFile(`.${pathName}`, (err, data) => { if (err) { res.writeHead(404, { 'content-type': 'text/html' }); res.end('<h1>Resource Not Found</h1>'); return; } // 根据资源类型设置Content-Type,示例为jpg,可按需扩展 res.writeHead(200, { 'content-type': 'image/jpeg' }); res.end(data); }); // Error }else{ // 原有逻辑不变 } })
3. 排查文件权限问题
如果在Linux/macOS环境下,检查模板文件、图片、data.json的读取权限,确保Node.js进程能访问:
chmod 644 ./template-*.html ./data.json ./img/*
4. 清除浏览器缓存
浏览器缓存旧错误响应可能导致403持续出现,按Ctrl+Shift+R(Windows/Linux)或Cmd+Shift+R(Mac)强制刷新页面。
5. 确认端口占用情况
虽然你更换过端口,可通过命令再次确认:
- Windows:
netstat -ano | findstr :3000
- Linux/macOS:
lsof -i :3000
若有进程占用,杀掉对应进程后重启服务器。
内容的提问来源于stack exchange,提问作者ConfusedGuy
相关产品推荐
相关产品推荐

