前端从Components目录调用server.js的/save-urls接口出现404错误
前端请求服务端接口返回404 Not Found的解决方法
核心问题:请求地址指向错误
前端代码中使用fetch("/save-urls")时,请求会发送到当前客户端所在的http://localhost:3000/save-urls,但你的服务端运行在5000端口,这是导致404的直接原因。
分步解决方案
1. 修正前端请求地址
将fetch的URL改为服务端的完整地址:
const saveUrlPair = async (originalUrl, shortenedUrl) => { try { console.log('inside try block'); // 替换为服务端的完整地址 const response = await fetch("http://localhost:5000/save-urls", { method: 'POST', mode: 'cors', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ originalUrl, shortUrl: shortenedUrl }), }); if (response.ok) { console.log('URL pair saved to DB'); } else { console.error('Failed to save URL pair to DB'); } } catch (error) { console.error('Error while saving URL pair:', error); } };
2. 完善服务端基础配置
确保你的server.js包含以下必要配置,否则即使地址正确也可能出现跨域或解析错误:
const express = require('express'); const cors = require('cors'); // 需要先安装:npm install cors const app = express(); // 1. 启用CORS,允许跨域请求 app.use(cors()); // 2. 解析JSON格式的请求体,否则req.body会为空 app.use(express.json()); // 3. 你的/save-urls路由 app.post('/save-urls', async (req, res) => { const { originalUrl, shortUrl} = req.body; console.log('1'); try{ console.log('2'); const url = new Url({originalUrl, shortUrl}); await url.save(); res.status(201).json({message: 'URLs saved successfully'}); }catch (error){ console.error(error); res.status(500).json({ message: 'Internal server error' }); } console.log('3'); }); // 4. 确保服务端监听5000端口 app.listen(5000, () => { console.log('Server running on port 5000'); });
3. 验证服务端状态
- 确认服务端已经启动,控制台输出
Server running on port 5000 - 可以直接用Postman或curl发送POST请求到
http://localhost:5000/save-urls,验证服务端是否正常响应
内容的提问来源于stack exchange,提问作者Mamba_24
相关产品推荐
相关产品推荐

