API works in POSTMAN, but not in code

Asked

Viewed 2,120 times

1

I am trying to access an API, by Postman, it works and returns json normally, already by code (using Vuejs + Axios) does not return, from CROSS error, how can this? where Axios returns normally?

let headers = {
        'Authorization': 'AUTENTICACAO BASIC',
        'Content-Type': 'application/json'
      }

axios.post('URL DA API', body, headers)
      .then(response => {
        console.log(response)
      })
      .catch(error => {
        console.log(error)
      })

In the body, I am sending the necessary data for the return.. Lembando that in Postman, returns the json correctly. The return is the error 401

  • Can you change the API to give your application access? If you can’t, you can add a proxy to your application.

  • you can specify the urls that can access your API, using the Annotation @Crossorigin(url) , that’s the reason for the error

2 answers

4


  • enable CORS, can be via Chrome pluggin or firefox.

2

The problem is with CORS, I could only solve the problem in this way:

var cors = require('cors');
app.use(cors({origin:true,credentials: true}));

And also setando the headers:

app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Origin', req.headers.origin);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Origin, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, X-Response-Time, X-PINGOTHER, X-CSRF-Token,Authorization');
    if (req.method === "OPTIONS") {
        return res.status(200).end();
    } else {
        next();
    }
});

Browser other questions tagged

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