React登录/注册页移动端请求后端出现Axios Network Error,PC端正常的问题求助
React登录/注册页移动端请求后端出现Axios Network Error,PC端正常的问题求助
我用MERN栈开发了一个带登录/注册功能的网站,PC端访问时登录、注册都能正常和后端交互,但在手机移动端打开网站时,每次触发登录或注册请求都会抛出AxiosError: NetworkError,试过StackOverflow上的一些方法但都没解决,想请教大家怎么修复这个问题,让网站能同时在PC和移动端正常运行。
前端React登录组件代码
import React, { useState } from "react"; import { Navbar } from "./header"; import axios from "axios"; export function Login(){ // 这里初始值不用数组,对象就够了,已调整 const [data,setdata] = useState({email:"",password:""}) const [mssg,setmssg] = useState("") function homepage(){ window.open('/homepage','_self') } function check_user(){ axios.post('http://localhost:4000/chekuser',data) .then(res=>{ console.log(res.data) setmssg(res.data) }) // 建议加上catch捕获错误,方便排查问题 .catch(err => console.error("请求出错啦:", err)) } const collect=(e)=>{ setdata({...data,[e.target.name]:e.target.value}) } return( <div> <Navbar></Navbar> <div id="form"> <h1 id="heading">Login</h1> <h3 className="entries">UserName</h3> <input name="email" onChange={collect} type="text" placeholder="Enter your email"></input> <h3 className="entries">Password</h3> <input name="password" onChange={collect} type="text" placeholder="Enter your Password"></input> <button onClick={check_user}> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" className ="bi bi-arrow-right" viewBox="0 0 16 16"> <path fillRule="evenodd" d="M1 8a.5.5 0 0 1 .5-.5h11.793l-3.147-3.146a.5.5 0 0 1 .708-.708l4 4a.5.5 0 0 1 0 .708l-4 4a.5.5 0 0 1-.708-.708L13.293 8.5H1.5A.5.5 0 0 1 1 8z"/> </svg> </button> <p>don't have account yet? <a href="/signin">click here</a></p> <p style={{color:"red"}}>{mssg}</p> </div> </div> ) }
后端Express+MongoDB代码
const express = require('express') const cors= require('cors') const bodyParser=require('body-parser') const mongoose=require('mongoose') const app=express(); app.use(cors()) app.use(bodyParser.json()) app.use(bodyParser.urlencoded({extended:true})) var model; async function connection(){ await mongoose.connect('mongodb+srv://ohyrt:321ransuytw@cluster0.t0anlxu.mongodb.net/quiet?retryWrites=true&w=majority',{useNewUrlParser:true}) .then( console.log("connected")) const schema=new mongoose.Schema({ Name:String, Email:String, Password:String, Username:String }) model = mongoose.model('newuser',schema) } connection() app.get('/',(req,res)=>{ res.send("Hello world") }) app.post('/creatuser',(req,res)=>{ const user=new model({ Name:req.body.Name, Email:req.body.Email, Password:req.body.Password, Username:req.body.Username }) user.save() // 这里需要返回响应,否则前端会一直等待请求结果 .then(() => res.send("用户创建成功")) .catch(err => res.status(500).send("创建失败:"+err.message)) }) app.post('/chekuser',async (req,res)=>{ let email = req.body.email; let password = req.body.password model.findOne({Email:email}) .then(user=>{ if(user){ if(user.Password===password){ console.log("user found") // 登录成功也要返回响应,不然前端收不到结果 res.send("登录成功") }else{ console.log("incorrect password") res.send("incorrect password") } }else{ console.log("no user") res.send("user didn't exsist") } }) // 加上catch处理数据库查询异常 .catch(err => { console.error("查询出错:", err) res.status(500).send("服务器内部错误") }) }) app.listen(4000, () => { console.log("服务器运行在http://localhost:4000") })
问题原因与解决方法
这个问题90%以上是移动端无法访问你电脑上的localhost地址导致的——localhost在移动端设备上指向的是它自己,而不是运行后端服务器的电脑。下面是具体修复步骤:
替换后端请求地址为电脑的局域网IP
- 先找到你电脑的局域网IP:
- Windows:打开命令提示符,输入
ipconfig,找IPv4地址(比如192.168.1.100) - Mac/Linux:打开终端,输入
ifconfig或ip addr,找对应的局域网IP
- Windows:打开命令提示符,输入
- 把前端代码中axios的请求地址从
http://localhost:4000/chekuser改成http://你的电脑局域网IP:4000/chekuser(比如http://192.168.1.100:4000/chekuser) - 确保你的手机和电脑连接在同一个WiFi网络下
- 先找到你电脑的局域网IP:
检查防火墙与端口开放
- 确认你电脑的防火墙没有阻止4000端口的入站请求,必要时可以临时关闭防火墙测试
完善后端响应逻辑
- 你的后端部分接口(比如
/creatuser)原本没有返回任何响应,前端会一直处于请求等待状态,容易引发超时或错误,已经在代码里补上了响应逻辑,建议保留
- 你的后端部分接口(比如
CORS配置优化(可选)
- 如果还是有跨域问题,可以指定CORS允许的来源,比如:
app.use(cors({ origin: ["http://你的前端IP:3000", "http://localhost:3000"], // 允许前端的访问地址 credentials: true }))
- 如果还是有跨域问题,可以指定CORS允许的来源,比如:
备注:内容来源于stack exchange,提问作者mm m




