首页 > 解决方案 > 从spring boot后端的reactjs中没有通过axios.get()请求获取数据

问题描述

我试图从 spring boot 控制器中获取数据,但数据没有出现在前端 ReactJS 中。

Spring Boot 控制器在 localhost 中工作正常,数据也出现在 localhost 中。

弹簧引导控制器:

package com.javaguidestutorials.reactspringboot.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.javaguidestutorials.reactspringboot.model.Employee;
import com.javaguidestutorials.reactspringboot.repository.EmployeeRepository;

@CrossOrigin(origins="http://localhost:3000/")
@RestController
@RequestMapping("/api/v1/")
public class EmployeeController {

    @Autowired
    private EmployeeRepository employeeRepository;
    
    // get all employees
    
    @GetMapping("/employees")
    public List<Employee> getAllEmployees()
    {
        
        return employeeRepository.findAll();
        
    }
    
    //Add employee
    
    @PostMapping("/employees")
    public Employee addEmployee(@RequestBody Employee employee)
    {
        return employeeRepository.save(employee); 
    }
}

ReactJS 员工服务:

import axios from 'axios';

const EMPLOYEE_API_BASE_URL = "http://localhost:9090/api/v1/employees";

class EmployeeService{

    getEmployees(){

        return axios.get(EMPLOYEE_API_BASE_URL);
    }
}

export default new EmployeeService()

附加到 EmployeeComponent 的 getEmployee 函数:

componentDidMount(){
        EmployeeService.getEmployees().then((res) => {
            this.setState({ employees : res.data });
        });
    }

包.json:

{
  "name": "react-springboot",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.9",
    "@testing-library/react": "^11.2.3",
    "@testing-library/user-event": "^12.6.2",
    "axios": "^0.21.1",
    "axios-cookiejar-support": "^1.0.1",
    "bootstrap": "^4.6.0",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.1",
    "tough-cookie": "^4.0.0",
    "web-vitals": "^0.2.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"
    ]
  }
}

得到错误喜欢:

xhr.js:177 GET http://localhost:9090/api/v1/employees 403
dispatchXhrRequest @ xhr.js:177
xhrAdapter @ xhr.js:13
dispatchRequest @ dispatchRequest.js:52
Promise.then (async)
request @ Axios.js:61
Axios.<computed> @ Axios.js:76
wrap @ bind.js:9
getEmployees @ EmployeeService.js:9
componentDidMount @ ListEmployeeComponent.jsx:20
commitLifeCycles @ react-dom.development.js:20663
commitLayoutEffects @ react-dom.development.js:23426
callCallback @ react-dom.development.js:3945
invokeGuardedCallbackDev @ react-dom.development.js:3994
invokeGuardedCallback @ react-dom.development.js:4056
commitRootImpl @ react-dom.development.js:23151
unstable_runWithPriority @ scheduler.development.js:646
runWithPriority$1 @ react-dom.development.js:11276
commitRoot @ react-dom.development.js:22990
performSyncWorkOnRoot @ react-dom.development.js:22329
scheduleUpdateOnFiber @ react-dom.development.js:21881
updateContainer @ react-dom.development.js:25482
(anonymous) @ react-dom.development.js:26021
unbatchedUpdates @ react-dom.development.js:22431
legacyRenderSubtreeIntoContainer @ react-dom.development.js:26020
render @ react-dom.development.js:26103
(anonymous) @ index.js:8
./src/index.js @ index.js:19
__webpack_require__ @ bootstrap:856
fn @ bootstrap:150
1 @ Footer.css?f24e:82
__webpack_require__ @ bootstrap:856
checkDeferredModules @ bootstrap:45
webpackJsonpCallback @ bootstrap:32
(anonymous) @ main.chunk.js:1
createError.js:16 Uncaught (in promise) Error: Request failed with status code 403
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:62)

Spring Boot GET REST API 在 post man 中运行良好:1

本地主机错误:ReactJS 中的 3000:2

标签: javascriptreactjsspring-bootaxios

解决方案


我弄错了。

解决方案:

我们需要从服务器端启用 CORS,以便我们可以从前端获取数据。

要启用此功能,我们需要在服务器端应用程序中添加一项功能。

我正在使用spring boot,所以您需要在主应用程序类中添加此功能

@Bean
  public WebMvcConfigurer corsConfigurer() {
      return new WebMvcConfigurer() {
          @Override
          public void addCorsMappings(CorsRegistry registry) {
              registry.addMapping("/**").allowedOrigins("http://localhost:3000");
          }
      };
  }

查看整个主应用程序类添加功能,如下所示:

package com.javaguidestutorials.reactspringboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@SpringBootApplication
public class ReactSpringbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(ReactSpringbootApplication.class, args);
    }

    
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:3000");
            }
        };
    }
}


推荐阅读