Search code examples
javascriptnode.jsaxiospassport-facebook

Difference between Fetch and Axios


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));

Solution

  • 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;
        });
    }