从localhost:5173向localhost:3000/register提交表单时Axios网络错误排查
问题描述
Chrome浏览器中从localhost:5173/register页面使用Axios提交表单时,持续出现网络错误:
POST http://localhost/3000/register net::ERR_CONNECTION_REFUSED
Firefox中则出现跨域请求被阻止的错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/3000/register. (Reason: CORS request did not succeed). Status code: (null)
使用VS Code的request.rest发送数据正常,但跨localhost提交数据失败,请求协助解决。
前端代码
import { useState } from "react"; import axios from "axios"; const registerUrl = "http://localhost:3000/register"; const Register = () => { const [input, setInput] = useState({ firstName: "", secondName: "", email: "", password: "", dateOfBirth: "", phoneNumber: "", state: "", }); const handleSubmit = async (e: any) => { e.preventDefault(); try { await axios.post(registerUrl, input); console.log(input); } catch (error) { console.log(error); } setInput({ firstName: "", secondName: "", }); }; return ( <> <div className="w-full sm:w-3/4 md:w-2/4 p-3 my-10 mx-auto bg-teal-300 shadow-sm shadow-gray-400"> <div className="w-3/4 mx-auto"> <h2 className="uppercase text-teal-800 text-xl pt-5"> Register User </h2> </div> <form onSubmit={handleSubmit}> <div className="flex flex-col gap-2 w-3/4 mx-auto p-3 text-teal-800"> <label htmlFor="">First Name</label> <input className="p-2 rounded-md bg-teal-100 outline-none focus:bg-teal-50" type="text" name="firstName" value={input.firstName} placeholder="First Name" onChange={(e) => setInput({ ...input, firstName: e.target.value }) } /> </div> <div className="flex flex-col gap-2 w-3/4 mx-auto p-3 text-teal-800"> <label htmlFor="">Second Name</label> <input className="p-2 rounded-md bg-teal-100 outline-none focus:bg-teal-50" type="text" name="secondName" value={input.secondName} placeholder="Second Name" onChange={(e) => setInput({ ...input, secondName: e.target.value }) } /> </div> <div className="flex justify-center mb-8"> <button type="submit" value="submit" className="bg-teal-600 w-3/4 mx-auto shadow-sm shadow-gray-300 hover:bg-teal-400 text-white p-4 border-none outline-none" > Submit </button> </div> </form> </div> </> ); }; export default Register;
后端代码
import express from "express"; import bcrypt from "bcrypt"; import cors from "cors"; const app = express(); app.use(express.json()); app.use(cors()); const newUser = []; app.get("/register", (req, res) => { res.send(newUser); }); app.post("/register", async (req, res) => { try { const hashedPassword = await bcrypt.hash(req.body.password, 10); const user = { firstName: req.body.firstName, secondName: req.body.secondName, password: hashedPassword, email: req.body.email, dateOfBirth: req.body.dateOfBirth, phoneNumber: req.body.phoneNumber, state: req.body.state, }; newUser.push(user); res.sendStatus(201); } catch (error) { console.log(error); } }); app.listen(3000);
解决方案
- 确认后端服务状态:先检查Express后端是否正常启动,终端中是否有服务运行的日志,没有的话执行启动命令(如
node server.js或npm run dev)。 - 修正URL格式:错误信息中显示请求地址为
http://localhost/3000/register,端口号位置错误,确保前端代码中registerUrl是http://localhost:3000/register,重启前端开发服务器。 - 明确配置CORS来源:将后端的
app.use(cors())替换为指定前端来源的配置,避免默认配置的潜在问题:app.use(cors({ origin: "http://localhost:5173", credentials: true })); - 前端配置代理(可选):如果是Vite项目,在
vite.config.js中添加代理,绕过跨域限制:
之后前端请求URL改为import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], server: { proxy: { '/api': { target: 'http://localhost:3000', changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, '') } } } })/api/register即可。 - 检查端口占用:用
netstat -ano | findstr :3000(Windows)或lsof -i :3000(Mac/Linux)检查3000端口是否被占用,杀掉占用进程后重启后端。
内容的提问来源于stack exchange,提问作者Misbahu Abubakar
相关产品推荐
相关产品推荐

