i have a problem when send access tocken in header axios.It returns the following error:
Access to XMLHttpRequest at ‘http://192.168.0.254:3333/api/DOTMobileApi/test’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
I wrote the following codes in react js:
localStorage.setItem("access_token","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmYW1pbHlfbmFtZSI6Itin2YbYtdin2LHZiiIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiLYp9mG2LXYp9ix2YoiLCJuYmYiOjE2NzY0NTMzNTUsImV4cCI6MTY3NjUzOTc1NSwiaXNzIjoibG9jYWxob3N0OjQ0MzQ2IiwiYXVkIjoibG9jYWxob3N0OjQ0MzQ2In0.4w2THPCrSvADow65fEm02H4NWUhGlFblaC6nB6uTgZ8")
let response= axios.get('http://192.168.0.254:3333/api/DOTMobileApi/test',{ headers:{ 'Authorization': Bearer ${localStorage.getItem("access_token")} } })
console.log(response)
3
Answers
i found solution . i have problem in backend .In fact,app.UseCors("CorsPolicy") should be written before app.UseAuthentication(); app.UseAuthorization()
You’ll have to enable CORS in your backend and add localhost:3000 as a trusted domain for this to work
Read about CORS.
You need to add your host to allowed origins.
In express without libs your have to do:
in app.js:
Question with you problem:
No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API
But if its not your API, you need to proxy your requests. Get data on your server and send it to your frontend