Problem with CORS even after setting header for Access-Control-Allow-Origin

Asked

Viewed 107 times

0

I have an app Vue staying in the Netlify and always when I try to achieve a request of the kind POST in my endpoint https://backend-app.herokuapp.com/clientes I get the following error:

Access to Xmlhttprequest at 'https://backend-app.herokuapp.com/clients' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested Resource.

As you can see, I get this error trying to access locally as well.

What I’ve tried in mine server.js:

const cors = require("cors");
app.use(cors());

Still in my server.js added Access-Control-Allow-Origin

app.use( ( req, res, next ) => {    
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Allow-Headers", "Authorization, Access-Control-Allow-Headers, Origin,X-Requested-With,Content-Type,Accept,content-type,application/json");
    res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS ")
    if ('OPTIONS' == req.method) {
      res.send(200);
    } else {
      next();
    }
  })

With no results, I tried this setting on my Cors

app.use(cors( {
    credentials: 'true',  
    origin: '*', 
    methods: 'GET, POST, PUT, DELETE, OPTIONS', 
    allowedHeaders: 'Authorization, Access-Control-Allow-Headers, Origin,X- Requested-With,Content-Type,Accept,content-type,application/json'
  }));

As I was still getting the error, I found in the forum Netlify (https://community.netlify.com/t/how-handle-cors-error-in-netlify/2721/8) the following suggestion: Create a file netlify.toml and try the following configuration:

[[redirects]]
  from = "/api/*"
  to = "https://backend-app.herokuapp.com/clientes/api/:splat"
  status = 200
# SPA router support.
[[redirects]]
  from = "/*"
  to = "/index.html"
  status = 200

But I still get the error of CORS. I believe this mistake is responsible for me not being able to be redirected to my path with this.$router.push("/tabela") when I submit my form to create a customer. That is, I type the customer data in the form and click register, with the console open I see that you get status pending and after a few seconds I get the error from CORS but the client was saved in my database. It is worth saying that all operations CRUD are working normally. Just at the time of creating a new client I have problems, the client is created but I am not redirected to my path because I get the error No 'Access-Control-Allow-Origin' header is present on the requested Resource

Does anyone know how to fix this problem?

No answers

Browser other questions tagged

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