Request with Axios and React blocked by CORS policy

Asked

Viewed 29,846 times

4

I’m trying to request an API using Axios:

  axios.post('http://api.teste.com.br/v1/getToken', {
      withCredentials: true,
      auth: {
          username: 'usuario',
          password: 'password'
      },
      headers: {                  
          "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Headers": "Authorization", 
          "Access-Control-Allow-Methods": "GET, POST, OPTIONS, PUT, PATCH, DELETE" ,
          "Content-Type": "application/json;charset=UTF-8"                   
      },
  }).then(resp => {  
    console.log(resp)
  })
  .catch(error => {          
      console.log(error)       
  })

But always presents the error:

Access to Xmlhttprequest at 'http://api.teste.com.br/v1/getToken' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight.

Is there any more configuration to do? Remembering that it is a third-party API and I can’t change the CORS on the server, and Postman works smoothly.

  • You’re calling axios.post(), would not be axios.get()?

  • I also found this strange as a post in the API documentation.

  • The API probably does not accept the value entered in the "Content-Type".

  • Your api is on that?

  • the api is third party, do not know what language it was developed. More on Postman I pass the "Content-Type" as application/json and it works.

  • The problem is that the CORS blocks the way you’re doing

  • That’s the problem is the CORS. I found the solution here : https://medium.com/@gigioSouza/resolvendo-o-problema-do-Cors-com-angular-2-e-o-angular-cli-7f7cb7aab3c2

  • Install this plugin on Crome: Allow-Control-Allow-Origin: *, from time to time I need to enable it to work in my applications locally when I do Viacep queries

  • Tries to change the Content-type for "application/x-www-form-urlencoded; charset=UTF-8" and see if anything changes. References: Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers and Differences in application/json and application/x-www-form-urlencoded.

  • Right, but the problem is that when you run npm run build, the proxy is ignored, and you get the same problem again. Until then you can’t find a solution to this, you’ve succeeded?

  • I found it strange because the error response is that it does not support the Content-Type you passed.

Show 6 more comments

4 answers

2

I had the same problem with a third-party API. It took me a long time to think more is simple. You can only access the api in the Back-end. If you go to the front end it is an error. In your Webservice go to the third party API. I added CORS to authorize.

Example to create an API in Node.js:

const express = require('express')
const axios = require('axios')
const app = express()
const cors = require('cors')

app.listen(3333)

app.use(cors())
app.get('/sms', (req,res)=>{   
     
    axios.post('https://apideterceiros/api',{    
        
            user: '1234',
            contact: [
              {
                number: '534543543',
                message: 'test message 1',
                externalid: '123456'
              }
            ],
            type: '2'      
    }).then(function(response){
        console.log(response.data)
        console.log(response.headers)
        console.log(response.status)
    }).catch(function(error){
        if(error){
            console.log(error)
        }
    })
    
    return res.json({teste:1})
}) 

1

What happened was this:

  1. The application tried to make a POST request to a server with another hostname.
  2. The browser has identified the POST method to another host; according to the specification, it means that it is a CORS request that needs a pre-flight request.
  3. The browser has made the pre-flight request, which is an OPTION request that checks whether the original request will be accepted by the server, sending the headers of that original request as well as defined in the question code (ps: the Access-Control headers-* is answered by the server, the client does not need to send them).
  4. The server received the pre-flight and responded with the Headers it accepts.
  5. The browser identified in the reply that the original request will not be allowed, as the Header Content-Type was not among the accepted and crashed before doing so.

The solution to this problem is to check the documentation of the api you are using to check the headers. I believe that because it is a request that uses HTTP Authentication, you do not need to submit the Content-Type application/json.

Do not forget to remove the Access-Control headers-*. These headers are answered by the server to meet the CORS specification.

If you want more details about the operation of CORS, this documentation from Mozilla is very good.

-1

I had the same problem, in the end just use the lib https://www.npmjs.com/package/cors.

Very simple to implement and will solve your problem, care only in the production environment not to leave everything released, with this lib you can release everything or some things just, it is worth a read in it.

I hope I’ve helped those who made it this far.

-2

Good afternoon!

Troubleshooting issue. I created a proxy in package.json file

"proxy": "http://api.teste.com.br/v1" and made the requisition so:

 axios.post('http://localhost:3000/getToken',  {username : "user", password : "password"})
  .then(resp => {  
      console.log(resp.data.data.authorization)
  })
  .catch(error => {          
      console.log(error)       
  })

This way the proxy means that tricks the CORS and has no more problems.

Browser other questions tagged

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