Solucionado (ver solução)
Solucionado
(ver solução)
7
respostas

No 'Access-Control-Allow-Origin' header is present on the requested resource.

Eu adicionei essa classe no meu projeto mas continua dando erro do CORS:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

Esse é meu componente de login no react:


import { useState } from "react"
import BotaoLogin from "../BotaoLogin"
import CampoTexto from "../CampoTexto"
import "./Login.css"
import axios from "axios"

const Login = () => {

    const [login, setLogin] = useState('')
    const [senha, setSenha] = useState('')

    const aoSubmeterFormulario = async (event) => {
        event.preventDefault();
        try {
            const response = await axios.post('http://localhost:8080/login', { login, senha });
            console.log(response.data);
        } catch (error) {
            console.error(error);
        }
    };


    return (
        <section className="bg">
            <div className="login">

                <form onSubmit={aoSubmeterFormulario}>
                    <CampoTexto value={login} obrigatorio={true} label="Login" onChange={(event)=>setLogin(event.target.value)} placeholder="" />
                    <CampoTexto value={senha} obrigatorio={true} label="Senha" onChange={(event) => setSenha(event.target.value)} placeholder="" />
                    <BotaoLogin className="botaoLogin">
                        Login
                    </BotaoLogin>
                </form>



            </div>

        </section>


    )
}

export default Login
7 respostas

Oi Thiago!

Precisa na API criar uma classe configurando o CORS, conforme demonstrado nessa atividade: https://cursos.alura.com.br/course/spring-boot-3-desenvolva-api-rest-java/task/116048

E se a API estiver com o Spring Security, precisa também liberar acesso nas configurações de segurança:

return http.csrf().disable()
    .cors()
    .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    //resto do código....

Agora pelo menos o react ta acessando a API quando eu dou o login no navegador: Insira aqui a descrição dessa imagem para ajudar na acessibilidade mas continua dando erro no console e o login nao passa:

AxiosError {message: 'Request failed with status code 403', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}code: "ERR_BAD_REQUEST"config: adapter: (2) ['xhr', 'http']data: "{\"login\":\"\",\"senha\":\"\"}"env: {FormData: ƒ, Blob: ƒ}headers: AxiosHeaders {Accept: 'application/json, text/plain, */*', Content-Type: 'application/json'}maxBodyLength: -1maxContentLength: -1method: "post"timeout: 0transformRequest: [ƒ]0: ƒ transformRequest(data, headers)length: 2name: "transformRequest"prototype: constructor: ƒ transformRequest(data, headers)length: 2name: "transformRequest"prototype: constructor: ƒ transformRequest(data, headers)length: 2name: "transformRequest"prototype: constructor: ƒ transformRequest(data, headers)length: 2name: "transformRequest"prototype: constructor: ƒ transformRequest(data, headers)length: 2name: "transformRequest"prototype: constructor: ƒ transformRequest(data, headers)length: 2name: "transformRequest"prototype: constructor: ƒ transformRequest(data, headers)length: 2name: "transformRequest"prototype: constructor: ƒ transformRequest(data, headers)[[Prototype]]: Objectarguments: (...)caller: (...)[[FunctionLocation]]: index.js:46[[Prototype]]: ƒ ()[[Prototype]]: Objectarguments: (...)caller: (...)[[FunctionLocation]]: index.js:46[[Prototype]]: ƒ ()[[Prototype]]: Objectarguments: (...)caller: (...)[[FunctionLocation]]: index.js:46[[Prototype]]: ƒ ()[[Prototype]]: Objectarguments: (...)caller: (...)[[FunctionLocation]]: index.js:46[[Prototype]]: ƒ ()[[Prototype]]: Objectarguments: (...)caller: (...)[[FunctionLocation]]: index.js:46[[Prototype]]: ƒ ()[[Prototype]]: Objectarguments: (...)caller: (...)[[FunctionLocation]]: index.js:46[[Prototype]]: ƒ ()[[Prototype]]: Objectarguments: (...)caller: (...)[[FunctionLocation]]: index.js:46[[Prototype]]: ƒ ()[[Prototype]]: Objectarguments: (...)caller: (...)[[FunctionLocation]]: index.js:46[[Prototype]]: ƒ ()[[Prototype]]: Objectarguments: (...)caller: (...)[[FunctionLocation]]: index.js:46[[Prototype]]: ƒ ()[[Prototype]]: Objectarguments: (...)caller: (...)[[FunctionLocation]]: index.js:46[[Prototype]]: ƒ ()[[Prototype]]: Objectarguments: (...)caller: (...)[[FunctionLocation]]: index.js:46[[Prototype]]: ƒ ()[[Prototype]]: Objectarguments: (...)caller: (...)[[FunctionLocation]]: index.js:46[[Prototype]]: ƒ ()[[Prototype]]: Objectarguments: (...)caller: (...)[[FunctionLocation]]: index.js:46[[Prototype]]: ƒ ()[[Prototype]]: Objectarguments: (...)caller: (...)[[FunctionLocation]]: index.js:46[[Prototype]]: ƒ ()[[Prototype]]: Objectarguments: (...)caller: (...)[[FunctionLocation]]: index.js:46[[Prototype]]: ƒ ()[[Prototype]]: Objectarguments: (...)caller: (...)[[FunctionLocation]]: index.js:46[[Prototype]]: ƒ ()[[Prototype]]: Objectarguments: (...)caller: (...)[[FunctionLocation]]: index.js:46[[Prototype]]: ƒ ()length: 1[[Prototype]]: Array(0)transformResponse: [ƒ]transitional: {silentJSONParsing: true, forcedJSONParsing: true, clarifyTimeoutError: false}url: "http://localhost:8080/login"validateStatus: ƒ validateStatus(status)xsrfCookieName: "XSRF-TOKEN"xsrfHeaderName: "X-XSRF-TOKEN"[[Prototype]]: Objectmessage: "Request failed with status code 403"name: "AxiosError"request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}response: {data: '', status: 403, statusText: '', headers: AxiosHeaders, config: {…}, …}stack: "AxiosError: Request failed with status code 403\n    at settle (http://localhost:3000/static/js/bundle.js:50002:12)\n    at XMLHttpRequest.onloadend (http://localhost:3000/static/js/bundle.js:48700:66)"[[Prototype]]: Error
aoSubmeterFormulario @ index.js:19
await in aoSubmeterFormulario (assíncrono)
callCallback @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291
executeDispatch @ react-dom.development.js:9041
processDispatchQueueItemsInOrder @ react-dom.development.js:9073
processDispatchQueue @ react-dom.development.js:9086
dispatchEventsForPlugins @ react-dom.development.js:9097
(anônimo) @ react-dom.development.js:9288
batchedUpdates$1 @ react-dom.development.js:26140
batchedUpdates @ react-dom.development.js:3991
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchDiscreteEvent @ react-dom.development.js:6430

Agora o CORS deu certo, mas o problema é acesso negado mesmo.

Essa requisição que você disparou foi pra fazer login? Verifica no Insomnia se ta dando erro também

No Insomnia tá devolvendo o token normal e dando 200. Testei as outras requisições com o token e todas tão funcionando. Eu tô até tomando o cuidado de copiar e colar o login e senha do Insomnia pros campos de login e senha.

Entendi. Pode ser que do frontend os dados nao estejam chegando certo.

Coloca isso no controller de autenticação:

@PostMapping
public ResponseEntity efetuarLogin(@RequestBody @Valid DadosAutenticacao dados) {
    System.out.println(dados);

    try {
        var authenticationToken = new UsernamePasswordAuthenticationToken(dados.login(), dados.senha());
        var authentication = manager.authenticate(authenticationToken);

        var tokenJWT = tokenService.gerarToken((Usuario) authentication.getPrincipal());

        return ResponseEntity.ok(new DadosTokenJWT(tokenJWT));
    } catch(Exception e) {
        e.printStackTrace();
        return ResponseEntity.badRequest().body("login inválido");
    }
}

E veja no console se imprime o login/senha e se acontece exception.

DadosAutenticacao[login=, senha=]
Hibernate: 
    select
        u1_0.id,
        u1_0.login,
        u1_0.senha 
    from
        usuarios u1_0 
    where
        u1_0.login=?
org.springframework.security.authentication.InternalAuthenticationServiceException: UserDetailsService returned null, which is an interface contract violation

acho que o problema é no front mesmo, pelo que eu entendi a api nao tá conseguindo puxar o login e senha, ta vindo como vazio, né?

solução!

Isso mesmo, não está chegando o usuário/senha e por isso a API retorna erro 403.