-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.
– Daniel Santos
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...
– LipESprY
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).
– Daniel Santos