Home > Net >  React Js problem with fetching axios to localhost database
React Js problem with fetching axios to localhost database

Time:12-29

I am building a personal project with react spring and now i work on the login page of my website. I try to check if in the localhost database( which is implemented in datagrip with postgres) exists the mail and the password that were introduced by user to login. I know there exists jwt, but i want to make it simpler because it's the first time when i am building such a big project. I get the axios error. I put it below.

Here is the code from the react login page

import React, {useEffect, useState} from 'react';
import TextField from '@mui/material/TextField';
import Container from '@mui/material/Container';
import { Paper } from '@mui/material';
import Button from '@mui/material/Button';
import axios from 'axios'


export default function BasicTextFieldslLogin() {
  
  const paperStyle={padding:'50px 20px', width:'600', margin:'20px auto'};
  const[email, setEmail] = useState('')
  const[password, setPassword] = useState('')
  const[posts, setPosts] = useState([])
  
  const handleClick = (e)=>{

    const person = {email, password}
    console.log(person)
  }

  useEffect(()=>{
        axios.get("http://localhost:8080/persons/login/{email}/{password}")
        .then(res=>{
            console.log(res)
            setPosts(res.data)
            console.log(posts)
        })
        .catch(err=>{
            console.log(err)
        })
  },[])

  return (
    <Container>
        <Paper elevation={3} style={paperStyle}>
            <h1 style={{color:"blue"}}>Login!</h1>
             <form className="formLogin" noValidate autoComplete="off">
                 <TextField sx = {{mb: 2}} required id="outlined-basic" label="Email" variant="outlined" fullWidth
                 value = {email}
                 onChange = {(e)=>setEmail(e.target.value)}
                 />
                 <TextField sx = {{mb: 2}} required id="outlined-basic" label="Password" type="password" variant="outlined" fullWidth
                 value = {password}
                 onChange = {(e)=>setPassword(e.target.value)}
                 />
                 <Button variant="contained" sx={{width:"200px", height:"50px", fontSize:"30px", fontWeight:"bold"}}
                 onClick={handleClick}
                 >Submit</Button>
             </form>
      </Paper>
    </Container>
  );
}

And this is the error i get:

Login:1 Access to XMLHttpRequest at 'http://localhost:8080/persons/login/{email}/{password}' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …} code : "ERR_NETWORK" config : {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} message : "Network Error" name : "AxiosError" request : XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} stack : "AxiosError: Network Error\n at XMLHttpRequest.handleError (http://localhost:3000/static/js/2.chunk.js:78416:14)" [[Prototype]] : Error

xhr.js:217 GET http://localhost:8080/persons/login/{email}/{password} net::ERR_FAILED 404

{email: 'mail', password: 'pass'} email : "mail" password : "pass" [[Prototype]] : Object constructor : ƒ Object() hasOwnProperty : ƒ hasOwnProperty() isPrototypeOf : ƒ isPrototypeOf() propertyIsEnumerable : ƒ propertyIsEnumerable() toLocaleString : ƒ toLocaleString() toString : ƒ toString() valueOf : ƒ valueOf() defineGetter : ƒ defineGetter() defineSetter : ƒ defineSetter() lookupGetter : ƒ lookupGetter() lookupSetter : ƒ lookupSetter() proto : (...) get proto : ƒ proto() set proto : ƒ proto()

CodePudding user response:

The reason is CORS origin error:

In any modern browser, Cross-Origin Resource Sharing (CORS) is a relevant specification with the emergence of HTML5 and JS clients that consume data via REST APIs.

You must enable Global Cross-Origin Resource Sharing (CORS) in Spring(Backend code). Check out: https://www.baeldung.com/spring-cors#global-cors-configuration

To fast fix, add @CrossOrigin annotation direct to Controller. For ex:

@CrossOrigin(origins = "http://localhost:3000")
@RestController
@RequestMapping("/account")
public class AccountController {

    @RequestMapping(method = RequestMethod.GET, path = "/{id}")
    public Account retrieve(@PathVariable Long id) {
        // ...
    }

    @RequestMapping(method = RequestMethod.DELETE, path = "/{id}")
    public void remove(@PathVariable Long id) {
        // ...
    }
}

CodePudding user response:

there is a CORS error in there update your backend so it will provide response to request originating from localhost:3000.

Ref. from your error response - 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

  • Related