skip to Main Content

can somebody explain to me why when I am using fetch and accessed my nodejs api – it is authorized but when I tried using axios to access my api – it is unauthorized.

This is the code I am using in fetch (It came from tutorial: https://medium.com/@alexanderleon/implement-social-authentication-with-react-restful-api-9b44f4714fa) Bec I am studying his way of authenticating using passport-facebook-token.

(client –>(login fbsdk)–> fb –> (access token)–> client –>(pass access token)–> nodejs api –> (get credentials) –> passport-fb-token –> (send credentials) –> nodejs api –> (credentials)–> client)

const tokenBlob = new Blob([JSON.stringify({access_token: response.accessToken}, null, 2)], {type : 'application/json'});
    const options = {
        method: 'POST',
        body: tokenBlob,
        mode: 'cors',
        cache: 'default'
    };
    fetch('http://localhost:4000/api/v1/auth/facebook', options).then(r => {
        const token = r.headers.get('x-auth-token');
        r.json().then(user => {
            if (token) {
                this.setState({isAuthenticated: true, user, token})
            }
        });
    })

This is the code of my axios

axios({
      method: 'post',
      url: 'http://localhost:4000/api/v1/auth/facebook',
      headers: {
        'Access-Control-Allow-Origin': '*',
      },
      data: {
        access_token: response.access_token
      }
  })
  .then((res) => console.log(res))
  .catch((err) => console.log(err));

2

Answers


  1. This blog should help you get your answer in detail:

    Fetch vs. Axios.js for making http requests

    Axios is a Javascript library used to make http requests from node.js
    or XMLHttpRequests from the browser and it supports the Promise API
    that is native to JS ES6. Another feature that it has over .fetch() is
    that it performs automatic transforms of JSON data.

    If you use .fetch() there is a two-step process when handing JSON
    data. The first is to make the actual request and then the second is
    to call the .json() method on the response.

    The .fetch() method is a great step in the right direction of getting
    http requests native in ES6, but just know that if you use it there
    are a couple of gotchas that might be better handled by third-party
    libraries like Axios.

    Login or Signup to reply.
  2. You should configure axios to use your token in one central place. For example

    export const configureAxios = (token) => {
        axios.interceptors.request.use(req => {
            // don't give our token to non-our servers
            if (isDomesticRequest(req.url)) {
                req.headers.Authorization = `Bearer ${token}`;
            }
            return req;
        });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search