
前端React代码中,fetch 请求使用了相对路径 /signup。这意味着浏览器会将请求发送到当前页面所在的域名和端口下的 /signup 路径。如果前端和后端运行在不同的端口或域名下,或者后端路由配置不正确,就会导致404错误。
要解决这个问题,需要确保前端 fetch 请求使用的URL是完整的、指向后端API的URL。
解决方案:使用完整的URL
在React组件的 handleSubmit 函数中,修改 fetch 请求的URL,使用完整的URL,包括协议、主机名和端口号。例如,如果你的后端服务器运行在 localhost:4000 上,则应将URL修改为 http://localhost:4000/signup。
const handleSubmit = (event) => {
event.preventDefault();
// Create a FormData object to send the form data
const formData = new FormData();
formData.append('name', name);
formData.append('password', password);
formData.append('image', image);
formData.append('address', address);
// Send the form data to the backend
fetch('http://localhost:4000/signup', { // 修改为完整的URL
method: 'POST',
body: formData,
})
.then((response) => {
if (response.ok) {
console.log('Form submitted successfully');
// Reset the form fields
setName('');
setPassword('');
setImage(null);
setAddress('');
} else {
console.error('Error submitting form');
}
})
.catch((error) => {
console.error('Network error:', error);
});
};注意事项:
CORS问题
除了URL问题,跨域资源共享(CORS)也可能导致请求失败。如果前端和后端运行在不同的域名下,浏览器会阻止跨域请求。
解决方案:
后端配置: 在Express.js后端使用 cors 中间件允许跨域请求。
const express = require("express");
const app = express();
const cors = require('cors');
app.use(cors()); // 启用CORS总结
解决MERN Stack用户注册表单404错误的关键在于确保前端 fetch 请求使用了正确的URL,指向后端API的注册路由。同时,需要注意CORS问题,确保后端允许跨域请求。通过检查URL和CORS配置,可以有效地解决此类问题。
更多关于CORS的信息,可以参考:How to solve CORS request did not succeed in express.js when react client try fetch data?
以上就是解决MERN Stack用户注册表单404错误的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号