React+Spring Boot跨域请求Axios报Network Error问题求助
React 对接 Spring Boot 时 Axios 仅返回 "Network Error" 排查方案
我正在开发React前端与Spring Boot后端对接的项目,调用接口时Axios只返回“Network Error”提示。已经在Spring Boot控制器添加了@CrossOrigin注解允许跨域,之前其他项目这么做都能正常运行,怀疑是不是遗漏了相关Bean。以下是相关代码:
控制器代码
@CrossOrigin(origins = {"http://localhost:3000","http://localhost:3001"}) @RestController @RequestMapping("/authentification") public class AuthentificationController { @Autowired AuthentificationServices authentificationServices; @Autowired JasyptConfig jasyptConfig; @Autowired EmailService emailService; @GetMapping ... @GetMapping("/getBySighnIn/{email}/{password}") public Employee getauthentificationByEmailPassword(@PathVariable String email, @PathVariable String password){ ArrayList<Authentification> authentifications=authentificationServices.getauthentification(); try { for(int i=0;i<authentifications.size();i++){ if(email.equals(authentifications.get(i).getEmployee().getEmail()) &&password.equals(jasyptConfig.encryptor().decrypt(authentifications.get(i).getPassword())){ Employee employee=authentifications.get(i).getEmployee(); employee.setEmail(jasyptConfig.encryptor().decrypt(employee.getEmail())); employee.setPhoneNumber(jasyptConfig.encryptor().decrypt(employee.getPhoneNumber())); employee.setAddress(jasyptConfig.encryptor().decrypt(employee.getAddress())); //go back too return employee; } } } catch(NullPointerException e){ return null; } return null; } }
React 页面代码
import React, {Component,Fragment} from 'react'; import axios from 'axios'; import JSOG from 'jsog'; class SighnIn extends Component { constructor(props) { super(props); this.state = { email:"", password: "", message:"", employee:{} } this.sighnUp=this.sighnUp.bind(this); this.forgot=this.forgot.bind(this); } sighnUp=async ()=>{ let obj; let email=this.state.email; let password=this.state.password; await axios.get( 'http://localhost:8080/authentification/getBySighnIn/'+email+'/'+password) .then(res => { console.log("hi"); obj = JSOG.stringify(res.data); console.log("hi"); this.setState({employee:obj}); this.props.sighnIn(obj); }).catch( function (error) { console.log(error); }); } forgot=()=>{ this.props.hasForgot(); } render() { return( <div> <div> <form onSubmit={this.sighnUp}> <div> <label htmlFor="email">email:</label> <input type="text" id="email" onChange={(e)=>{this.setState({email:e.target.value})}} value={this.state.email} /> </div> <div> <label htmlFor="password">password:</label> <input type="text" id="password" onChange={(e)=>{this.setState({password:e.target.value})}} value={this.state.password} /> </div> <input type="submit" value="submit" /> </form></div> <div> <button onClick={this.forgot}>forgot password</button> </div> </div>); } } // Exporting the component export default SighnIn;
app.properties 配置
##for crud application # DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) spring.datasource.url=jdbc:mysql://localhost:3306/divinapopina?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false spring.datasource.username=root spring.datasource.password=**** ## dont know what this one does spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # Hibernate # The SQL dialect makes Hibernate generate better SQL for the chosen database spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect # Hibernate ddl auto (create, create-drop, validate, update) spring.jpa.hibernate.ddl-auto = update logging.level.org.hibernate.SQL=DEBUG logging.level.org.hibernate.type=TRACE ##for log in spring.jpa.show-sql=true #gmail spring.mail.default-encoding=UTF-8 spring.mail.host=smtp.gmail.com spring.mail.username=realtyking66@gmail.com spring.mail.password=**** spring.mail.port=587 spring.mail.protocol=smtp spring.mail.test-connection=false spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true
package.json 配置
{ "name": "divinapopinaemployeeportal", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^5.16.5", "@testing-library/react": "^13.4.0", "@testing-library/user-event": "^13.5.0", "axios": "^1.3.2", "bootstrap": "^5.2.3", "jsog": "^1.0.7", "react": "^18.2.0", "react-cookie": "^4.1.1", "react-dom": "^18.2.0", "react-router-dom": "^6.8.1", "react-scripts": "5.0.1", "reactstrap": "^9.1.5", "web-vitals": "^2.1.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "proxy":"http://localhost:3000" }
排查与修复步骤
修正React代理配置
package.json中的proxy配置指向错误,应该改为后端服务地址http://localhost:8080,修改后:"proxy":"http://localhost:8080"重启React项目后,Axios请求可简化为相对路径:
await axios.get('/authentification/getBySighnIn/'+email+'/'+password)替换为全局跨域配置
控制器级别的@CrossOrigin可能存在覆盖或遗漏,创建全局跨域配置类确保生效:@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:3000", "http://localhost:3001") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .allowCredentials(true); } }验证后端接口可用性
直接在浏览器或Postman访问http://localhost:8080/authentification/getBySighnIn/测试邮箱/测试密码,确认接口本身能正常返回数据,排除后端业务逻辑异常。阻止表单默认提交行为
当前表单提交会触发页面刷新,中断Axios请求,修改sighnUp方法:sighnUp=async (e)=>{ e.preventDefault(); // 阻止默认提交 let obj; let email=this.state.email; let password=this.state.password; await axios.get( '/authentification/getBySighnIn/'+email+'/'+password) .then(res => { console.log("hi"); obj = JSOG.stringify(res.data); console.log("hi"); this.setState({employee:obj}); this.props.sighnIn(obj); }).catch( function (error) { console.log(error); }); }确认Jasypt Bean实例化
确保JasyptConfig类添加@Configuration注解,且加密器Bean正确定义:@Configuration public class JasyptConfig { @Bean("jasyptStringEncryptor") public StringEncryptor encryptor() { PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor(); SimpleStringPBEConfig config = new SimpleStringPBEConfig(); config.setPassword("你的加密密钥"); // 建议从配置文件读取 config.setAlgorithm("PBEWithMD5AndDES"); config.setKeyObtentionIterations("1000"); config.setPoolSize("1"); config.setProviderName("SunJCE"); config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator"); config.setStringOutputType("base64"); encryptor.setConfig(config); return encryptor; } }
内容的提问来源于stack exchange,提问作者jonathan Daboush
相关产品推荐
相关产品推荐

