Blocked cross-origin request - JS/CORS/AXIOS

Asked

Viewed 2,457 times

-1

I am using an API (Axios) to connect my application backend to frontend, however, I am not able to give POST (register a new record) on one of the pages because Mozilla Firefox blocks cross-origin requests. I searched the internet, I understood why the problem but I still don’t understand how to solve it using Javascript and the API.

The error message:

Blocked cross-origin request: Same Origin Policy (Same Origin Policy) prevents reading the remote resource at http://localhost:3333/Ongs. (Reason: CORS header 'Access-Control-Allow-Origin' is not present).

(My frontend is running on http://localhost:3000/Register)

Follow the API code:

export default function Register(){
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [whatsapp, setWhatsapp] = useState('');
const [city, setCity] = useState('');
const [uf, setUf] = useState('');

async function handleRegister(e){ //função que será executada a todo submit
    e.preventDefault(); //Evita que o form recarregue a cada submit

    const data = {
        name,
        email,
        whatsapp,
        city,
        uf,
    };

    try{

        const response = await api.post('ongs', data); //por padrão, o axios já envia pro backend em formato json
        alert(`Seu ID de acesso: ${response.data.id}`);
    }catch (err){
        alert('Erro no cadastro, tente novamente.');
    }
}

return (inputs aqui);

As I said before, I realized that this error is associated with the absence of Access-Control-Allow-Origin=true in the request header, but how do I do this?

  • No, because the link only explain how it is done in Swift and Php (or using Chrome directly), in my case, I’m using Firefox and was looking for the equivalent solution in JS.

  • Although blocking is done in the browser, the configuration must be done on the server. One should configure the headers regardless of the language you will (are) use (ndo). Despite the possibility of disabling CORS in the browser, it is impossible to force your customers to do so. Or is it? See if any of these questions attend to you...

  • Yes, it is unviable. The only way would be configuring in the application itself, setting the headers, but do not know how to do it using JS (Node/Axios).

1 answer

1

Setting up Cors should be done in the backend to access your endpoints. I don’t know how your backend was done... However, it follows an example using Node and Express:

Before, you should add Cors dependency;

npm install cors
const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors()); // habilitando o cors da aplicação para todas as rotas

app.listen(8081, () => {
  console.log('CORS-enabled web server listening on port 8081')
})

I do not know if it was useful, but this would be an implementation in Node... I hope to have helped :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.