Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

javascript - React and Axios : Axios Can't Access Java/SpringBoot REST Backend Service Because of CORS Policy

I am using React, node.js and this is my first time using Axios to connect to my Java/SpringBoot Rest GET service (fetch all) on localhost:8080 which returns a list of saved users as a JSON array. What I am trying to achieve is to successfully connect and retrieve the REST data with Axios GET but I got the following error:

Failed to compile

srcApp.js
  Line 16:7:   'setIsLoaded' is not defined  no-undef
  Line 17:7:   'setRowData' is not defined   no-undef
  Line 35:13:  'rowData' is not defined      no-undef

I suspect perhaps I haven't imported some components properly?

Here is my code :

import React, { useEffect } from "react";
import { axios } from 'axios';
import { jsonServerRestClient, Admin, Resource, Delete } from 'admin-on-rest';
import { DataGrid } from '@material-ui/data-grid';

 
export default function App() {


useEffect(() => {
  const apiurl = "http://localhost:8080/user/all";
  axios
    .get(apiurl)
    .then((response) => response.data)
    .then((data) => {
      setIsLoaded(true);
      setRowData(data);
    });
}, []);



const columns = [
  { field: "id", headerName: "ID", width: 10 },
  { field: "userName", headerName: "Name", width: 170 },
  { field: "userTelNo", headerName: "Tel No", width: 70 },
  { field: "userEmail", headerName: "EMail", width: 100 },
  { field: "userRole", headerName: "Role", width: 100 },
];



  return( 
    <DataGrid
      rows={rowData}
      columns={columns}
      id="id"
      pageSize={15}
      checkboxSelection
    />
  );

  }

I confirmed that upon checking the GET URL on my browser address bar (http://localhost:8080/user/all), the JSON is returning properly (as an array of JSONs) as shown below:

[{"id":1,"userName":"admin","userPassword":"admin123","userTelNo":"012-104-1001","userEmail":"[email protected]","userRole":"管理员","loginDateTime":"2021-01-25T09:57:38","entryDateTime":"2021-01-25T09:57:31","updateDateTime":"2021-01-25T09:57:40"},

{"id":2,"userName":"t","userPassword":"admin123","userTelNo":"","userEmail":"","userRole":"开发 人员","loginDateTime":"2021-01-25T11:15:53","entryDateTime":"2021-01-25T11:15:53","updateDateTime":"2021-01-25T11:15:53"},

{"id":3,"userName":"324","userPassword":"43444","userTelNo":"4334","userEmail":"344","userRole":"开发 人员","loginDateTime":"2021-01-25T23:12:38","entryDateTime":"2021-01-25T23:12:38","updateDateTime":"2021-01-25T23:12:38"}]

EDIT:

I've simplified my program a bit to get to the bottom of things as below and I found out that it seems to be a CORS issue from the server backend :

Simplified code:

import React from 'react';
import { axios } from 'axios';

 
export default function App() {

  const axios = require('axios').default;

  axios.get('http://localhost:8080/user/all')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });


  return null;


  }

The error message from Chrome Developer Tools (F12) :

Access to XMLHttpRequest at 'http://localhost:8080/user/all' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

so I guess I have to find a way for my Java SpringBoot backend user REST service to "give permission" for http://localhost:3000 to access it. Anyone know how can this be done?

question from:https://stackoverflow.com/questions/65895332/react-and-axios-axios-cant-access-java-springboot-rest-backend-service-becaus

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you mentioned you are getting this in chrome console

Access to XMLHttpRequest at 'http://localhost:8080/user/all' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

that is cors issue you are facing, To solve this, at the spring boot side, you have to use CrossOrigin annotation which let the backend serve the request from other origin also depending upon origins you want to allow.
so add this annotation

@CrossOrigin(origins = "http://localhost:3000")

to your RestController class
If you want to allow request from any origin on spring boot server, then modify the cross-origin annotation to

@CrossOrigin(origins = "*")

or

@CrossOrigin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...