POST请求报TypeError: Failed to fetch问题排查求助
POST请求抛出"TypeError: Failed to fetch"且stalled的排查方案
问题背景
我正在开发一个JavaScript+Node.js项目,GET请求运行正常,但POST请求持续抛出"TypeError: Failed to fetch"错误,浏览器Network面板的Timing标签显示请求处于stalled状态无法完成。已添加CORS头,且表单提交时已使用event.preventDefault(),但问题仍未解决。
前端请求代码
async function handleFormSubmit(postData) { // Send a POST request to your API endpoint await fetch("http://localhost:3000/api/submit", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(postData), }) .then((response) => response.json()) .then((data) => { console.log("POST Response:", data); }) .catch((error) => { console.error("POST Error:", error); }); } postForm.addEventListener("submit", (event) => { event.preventDefault(); const formData = new FormData(postForm); const postData = { model_id: formData.get("model_id"), prompt: formData.get("prompt"), bad_response: formData.get("bad_response"), }; handleFormSubmit(postData); });
server.js代码
const modelRoutes = require('./src/routes/modelRoutes'); app.use(cors()); app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', 'http://localhost:3000'); // Replace '*' with your allowed origin res.header( 'Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept', ); next(); }); app.use(bodyParser.json({ limit: '10mb', extended: true })); app.use(bodyParser.urlencoded({ limit: '10mb', extended: true })); app.use(express.static(path.join(__dirname, './public'))); app.use(express.json()); app.use('/api', modelRoutes);
modelRoutes.js代码
router.post('/submit', hallucinationController.submitHallucination);
控制器代码
const submitHallucination = async (req, res) => { try { const { model_id, prompt, bad_response } = req.body; // Use the public key to verify the request (optional). console.log('controller:', prompt); //Here cannot reach for now const mId = mongoose.Types.ObjectId(model_id); const newSave = { model_id: mId, prompt: prompt, bad_response: bad_response, p_tuned: false, }; // Save the hallucination data to your database (e.g., HALLUCINATION table). const hallucination = new Hallucination(newSave); const saved = await hallucination.save(); // Return a success message. Utilities.apiResponse( res, 200, 'Hallucination submitted successfully!', {}, ); } catch (error) { console.log('error:', error); Utilities.apiResponse(res, 500, error); } };
排查方向
- CORS配置冲突:同时使用
app.use(cors())和自定义CORS中间件会导致响应头重复,浏览器可能拒绝处理。删掉自定义的CORS中间件,改用带参数的cors配置:app.use(cors({ origin: 'http://localhost:3000' })); - 服务器未正常响应:请求stalled通常意味着服务器未返回响应,检查:
- 服务器控制台是否有报错,比如
mongoose.Types.ObjectId(model_id)的格式错误(若model_id不是有效ObjectId字符串会抛出异常); - 确认
Utilities.apiResponse方法是否正确调用了res.send()/res.json()结束响应,若方法未正确发送响应,请求会一直挂起。
- 服务器控制台是否有报错,比如
- 端口与同源问题:确保前端页面运行端口与服务器(3000)不同,避免端口占用或同源冲突。
- 异步处理优化:前端
handleFormSubmit的async/await与.then混用易引发问题,统一风格并在submit事件中处理异常:postForm.addEventListener("submit", async (event) => { event.preventDefault(); const formData = new FormData(postForm); const postData = { model_id: formData.get("model_id"), prompt: formData.get("prompt"), bad_response: formData.get("bad_response"), }; try { await handleFormSubmit(postData); } catch (err) { console.error('Submit failed:', err); } }); - 表单数据有效性:在前端打印
postData,确认所有字段都有有效值,避免JSON.stringify后生成异常格式的请求体。
内容的提问来源于stack exchange,提问作者Claire
相关产品推荐
相关产品推荐

